From cbc39027a4cc9fa304209452a1977d0a5a33c9ed Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 14 May 2021 04:59:03 +0000 Subject: [PATCH 1/2] chore: upgrade gapic-generator-python to 0.46.3 PiperOrigin-RevId: 373649163 Source-Link: https://github.com/googleapis/googleapis/commit/7e1b14e6c7a9ab96d2db7e4a131981f162446d34 Source-Link: https://github.com/googleapis/googleapis-gen/commit/0a3c7d272d697796db75857bac73905c68e498c3 --- 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_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 | 20 + .../dialogflow_v2/session_entity_types.rst | 10 + .../v2/docs/dialogflow_v2/sessions.rst | 6 + .../v2/docs/dialogflow_v2/types.rst | 7 + .../v2/docs/dialogflow_v2/versions.rst | 10 + owl-bot-staging/v2/docs/index.rst | 7 + .../v2/google/cloud/dialogflow/__init__.py | 419 ++ .../v2/google/cloud/dialogflow/py.typed | 2 + .../v2/google/cloud/dialogflow_v2/__init__.py | 420 ++ .../cloud/dialogflow_v2/gapic_metadata.json | 1039 +++++ .../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 | 922 ++++ .../dialogflow_v2/services/agents/client.py | 1112 +++++ .../dialogflow_v2/services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 305 ++ .../services/agents/transports/grpc.py | 522 +++ .../agents/transports/grpc_asyncio.py | 526 +++ .../services/answer_records/__init__.py | 22 + .../services/answer_records/async_client.py | 370 ++ .../services/answer_records/client.py | 557 +++ .../services/answer_records/pagers.py | 140 + .../answer_records/transports/__init__.py | 33 + .../answer_records/transports/base.py | 198 + .../answer_records/transports/grpc.py | 277 ++ .../answer_records/transports/grpc_asyncio.py | 281 ++ .../services/contexts/__init__.py | 22 + .../services/contexts/async_client.py | 703 ++++ .../dialogflow_v2/services/contexts/client.py | 890 ++++ .../dialogflow_v2/services/contexts/pagers.py | 140 + .../services/contexts/transports/__init__.py | 33 + .../services/contexts/transports/base.py | 255 ++ .../services/contexts/transports/grpc.py | 383 ++ .../contexts/transports/grpc_asyncio.py | 387 ++ .../conversation_profiles/__init__.py | 22 + .../conversation_profiles/async_client.py | 594 +++ .../services/conversation_profiles/client.py | 817 ++++ .../services/conversation_profiles/pagers.py | 140 + .../transports/__init__.py | 33 + .../conversation_profiles/transports/base.py | 241 ++ .../conversation_profiles/transports/grpc.py | 368 ++ .../transports/grpc_asyncio.py | 372 ++ .../services/conversations/__init__.py | 22 + .../services/conversations/async_client.py | 625 +++ .../services/conversations/client.py | 830 ++++ .../services/conversations/pagers.py | 263 ++ .../conversations/transports/__init__.py | 33 + .../services/conversations/transports/base.py | 240 ++ .../services/conversations/transports/grpc.py | 381 ++ .../conversations/transports/grpc_asyncio.py | 385 ++ .../services/documents/__init__.py | 22 + .../services/documents/async_client.py | 773 ++++ .../services/documents/client.py | 960 +++++ .../services/documents/pagers.py | 140 + .../services/documents/transports/__init__.py | 33 + .../services/documents/transports/base.py | 261 ++ .../services/documents/transports/grpc.py | 423 ++ .../documents/transports/grpc_asyncio.py | 427 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 1195 ++++++ .../services/entity_types/client.py | 1383 ++++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 318 ++ .../services/entity_types/transports/grpc.py | 522 +++ .../entity_types/transports/grpc_asyncio.py | 526 +++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 607 +++ .../services/environments/client.py | 808 ++++ .../services/environments/pagers.py | 262 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 254 ++ .../services/environments/transports/grpc.py | 393 ++ .../environments/transports/grpc_asyncio.py | 397 ++ .../services/fulfillments/__init__.py | 22 + .../services/fulfillments/async_client.py | 345 ++ .../services/fulfillments/client.py | 532 +++ .../fulfillments/transports/__init__.py | 33 + .../services/fulfillments/transports/base.py | 198 + .../services/fulfillments/transports/grpc.py | 276 ++ .../fulfillments/transports/grpc_asyncio.py | 280 ++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 871 ++++ .../dialogflow_v2/services/intents/client.py | 1067 +++++ .../dialogflow_v2/services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 276 ++ .../services/intents/transports/grpc.py | 433 ++ .../intents/transports/grpc_asyncio.py | 437 ++ .../services/knowledge_bases/__init__.py | 22 + .../services/knowledge_bases/async_client.py | 601 +++ .../services/knowledge_bases/client.py | 788 ++++ .../services/knowledge_bases/pagers.py | 140 + .../knowledge_bases/transports/__init__.py | 33 + .../knowledge_bases/transports/base.py | 241 ++ .../knowledge_bases/transports/grpc.py | 356 ++ .../transports/grpc_asyncio.py | 360 ++ .../services/participants/__init__.py | 22 + .../services/participants/async_client.py | 766 ++++ .../services/participants/client.py | 983 +++++ .../services/participants/pagers.py | 140 + .../participants/transports/__init__.py | 33 + .../services/participants/transports/base.py | 274 ++ .../services/participants/transports/grpc.py | 414 ++ .../participants/transports/grpc_asyncio.py | 418 ++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 629 +++ .../services/session_entity_types/client.py | 816 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 241 ++ .../session_entity_types/transports/grpc.py | 374 ++ .../transports/grpc_asyncio.py | 378 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 396 ++ .../dialogflow_v2/services/sessions/client.py | 600 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 204 + .../services/sessions/transports/grpc.py | 292 ++ .../sessions/transports/grpc_asyncio.py | 296 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 639 +++ .../dialogflow_v2/services/versions/client.py | 826 ++++ .../dialogflow_v2/services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 241 ++ .../services/versions/transports/grpc.py | 361 ++ .../versions/transports/grpc_asyncio.py | 365 ++ .../cloud/dialogflow_v2/types/__init__.py | 398 ++ .../google/cloud/dialogflow_v2/types/agent.py | 459 ++ .../dialogflow_v2/types/answer_record.py | 350 ++ .../cloud/dialogflow_v2/types/audio_config.py | 463 ++ .../cloud/dialogflow_v2/types/context.py | 298 ++ .../cloud/dialogflow_v2/types/conversation.py | 390 ++ .../dialogflow_v2/types/conversation_event.py | 79 + .../types/conversation_profile.py | 834 ++++ .../cloud/dialogflow_v2/types/document.py | 372 ++ .../cloud/dialogflow_v2/types/entity_type.py | 561 +++ .../cloud/dialogflow_v2/types/environment.py | 459 ++ .../cloud/dialogflow_v2/types/fulfillment.py | 201 + .../google/cloud/dialogflow_v2/types/gcs.py | 25 + .../types/human_agent_assistant_event.py | 61 + .../cloud/dialogflow_v2/types/intent.py | 1611 +++++++ .../dialogflow_v2/types/knowledge_base.py | 225 + .../cloud/dialogflow_v2/types/participant.py | 836 ++++ .../cloud/dialogflow_v2/types/session.py | 964 +++++ .../types/session_entity_type.py | 251 ++ .../dialogflow_v2/types/validation_result.py | 93 + .../cloud/dialogflow_v2/types/version.py | 265 ++ .../cloud/dialogflow_v2/types/webhook.py | 230 + owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 132 + .../scripts/fixup_dialogflow_v2_keywords.py | 257 ++ owl-bot-staging/v2/setup.py | 53 + 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 | 3145 ++++++++++++++ .../dialogflow_v2/test_answer_records.py | 1661 ++++++++ .../unit/gapic/dialogflow_v2/test_contexts.py | 2595 ++++++++++++ .../test_conversation_profiles.py | 2458 +++++++++++ .../gapic/dialogflow_v2/test_conversations.py | 2618 ++++++++++++ .../gapic/dialogflow_v2/test_documents.py | 2655 ++++++++++++ .../gapic/dialogflow_v2/test_entity_types.py | 3574 ++++++++++++++++ .../gapic/dialogflow_v2/test_environments.py | 2420 +++++++++++ .../gapic/dialogflow_v2/test_fulfillments.py | 1487 +++++++ .../unit/gapic/dialogflow_v2/test_intents.py | 3088 ++++++++++++++ .../dialogflow_v2/test_knowledge_bases.py | 2378 +++++++++++ .../gapic/dialogflow_v2/test_participants.py | 2957 +++++++++++++ .../test_session_entity_types.py | 2369 +++++++++++ .../unit/gapic/dialogflow_v2/test_sessions.py | 1381 ++++++ .../unit/gapic/dialogflow_v2/test_versions.py | 2391 +++++++++++ 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 | 7 + .../docs/dialogflow_v2beta1/versions.rst | 10 + owl-bot-staging/v2beta1/docs/index.rst | 7 + .../google/cloud/dialogflow/__init__.py | 463 ++ .../v2beta1/google/cloud/dialogflow/py.typed | 2 + .../cloud/dialogflow_v2beta1/__init__.py | 464 +++ .../dialogflow_v2beta1/gapic_metadata.json | 1099 +++++ .../google/cloud/dialogflow_v2beta1/py.typed | 2 + .../dialogflow_v2beta1/services/__init__.py | 15 + .../services/agents/__init__.py | 22 + .../services/agents/async_client.py | 930 +++++ .../services/agents/client.py | 1120 +++++ .../services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 305 ++ .../services/agents/transports/grpc.py | 524 +++ .../agents/transports/grpc_asyncio.py | 528 +++ .../services/answer_records/__init__.py | 22 + .../services/answer_records/async_client.py | 457 ++ .../services/answer_records/client.py | 645 +++ .../services/answer_records/pagers.py | 140 + .../answer_records/transports/__init__.py | 33 + .../answer_records/transports/base.py | 212 + .../answer_records/transports/grpc.py | 304 ++ .../answer_records/transports/grpc_asyncio.py | 308 ++ .../services/contexts/__init__.py | 22 + .../services/contexts/async_client.py | 731 ++++ .../services/contexts/client.py | 918 ++++ .../services/contexts/pagers.py | 140 + .../services/contexts/transports/__init__.py | 33 + .../services/contexts/transports/base.py | 255 ++ .../services/contexts/transports/grpc.py | 384 ++ .../contexts/transports/grpc_asyncio.py | 388 ++ .../conversation_profiles/__init__.py | 22 + .../conversation_profiles/async_client.py | 594 +++ .../services/conversation_profiles/client.py | 817 ++++ .../services/conversation_profiles/pagers.py | 140 + .../transports/__init__.py | 33 + .../conversation_profiles/transports/base.py | 241 ++ .../conversation_profiles/transports/grpc.py | 368 ++ .../transports/grpc_asyncio.py | 372 ++ .../services/conversations/__init__.py | 22 + .../services/conversations/async_client.py | 703 ++++ .../services/conversations/client.py | 908 ++++ .../services/conversations/pagers.py | 263 ++ .../conversations/transports/__init__.py | 33 + .../services/conversations/transports/base.py | 254 ++ .../services/conversations/transports/grpc.py | 409 ++ .../conversations/transports/grpc_asyncio.py | 413 ++ .../services/documents/__init__.py | 22 + .../services/documents/async_client.py | 845 ++++ .../services/documents/client.py | 1033 +++++ .../services/documents/pagers.py | 140 + .../services/documents/transports/__init__.py | 33 + .../services/documents/transports/base.py | 275 ++ .../services/documents/transports/grpc.py | 454 ++ .../documents/transports/grpc_asyncio.py | 458 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 1224 ++++++ .../services/entity_types/client.py | 1412 +++++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 318 ++ .../services/entity_types/transports/grpc.py | 519 +++ .../entity_types/transports/grpc_asyncio.py | 523 +++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 607 +++ .../services/environments/client.py | 808 ++++ .../services/environments/pagers.py | 262 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 254 ++ .../services/environments/transports/grpc.py | 393 ++ .../environments/transports/grpc_asyncio.py | 397 ++ .../services/fulfillments/__init__.py | 22 + .../services/fulfillments/async_client.py | 348 ++ .../services/fulfillments/client.py | 535 +++ .../fulfillments/transports/__init__.py | 33 + .../services/fulfillments/transports/base.py | 198 + .../services/fulfillments/transports/grpc.py | 276 ++ .../fulfillments/transports/grpc_asyncio.py | 280 ++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 889 ++++ .../services/intents/client.py | 1085 +++++ .../services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 276 ++ .../services/intents/transports/grpc.py | 434 ++ .../intents/transports/grpc_asyncio.py | 438 ++ .../services/knowledge_bases/__init__.py | 22 + .../services/knowledge_bases/async_client.py | 615 +++ .../services/knowledge_bases/client.py | 802 ++++ .../services/knowledge_bases/pagers.py | 140 + .../knowledge_bases/transports/__init__.py | 33 + .../knowledge_bases/transports/base.py | 241 ++ .../knowledge_bases/transports/grpc.py | 370 ++ .../transports/grpc_asyncio.py | 374 ++ .../services/participants/__init__.py | 22 + .../services/participants/async_client.py | 1007 +++++ .../services/participants/client.py | 1235 ++++++ .../services/participants/pagers.py | 262 ++ .../participants/transports/__init__.py | 33 + .../services/participants/transports/base.py | 316 ++ .../services/participants/transports/grpc.py | 533 +++ .../participants/transports/grpc_asyncio.py | 537 +++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 649 +++ .../services/session_entity_types/client.py | 836 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 241 ++ .../session_entity_types/transports/grpc.py | 374 ++ .../transports/grpc_asyncio.py | 378 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 406 ++ .../services/sessions/client.py | 619 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 204 + .../services/sessions/transports/grpc.py | 292 ++ .../sessions/transports/grpc_asyncio.py | 296 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 641 +++ .../services/versions/client.py | 828 ++++ .../services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 241 ++ .../services/versions/transports/grpc.py | 362 ++ .../versions/transports/grpc_asyncio.py | 366 ++ .../dialogflow_v2beta1/types/__init__.py | 444 ++ .../cloud/dialogflow_v2beta1/types/agent.py | 492 +++ .../dialogflow_v2beta1/types/answer_record.py | 392 ++ .../dialogflow_v2beta1/types/audio_config.py | 507 +++ .../cloud/dialogflow_v2beta1/types/context.py | 327 ++ .../dialogflow_v2beta1/types/conversation.py | 462 ++ .../types/conversation_event.py | 78 + .../types/conversation_profile.py | 818 ++++ .../dialogflow_v2beta1/types/document.py | 525 +++ .../dialogflow_v2beta1/types/entity_type.py | 586 +++ .../dialogflow_v2beta1/types/environment.py | 459 ++ .../dialogflow_v2beta1/types/fulfillment.py | 201 + .../cloud/dialogflow_v2beta1/types/gcs.py | 62 + .../types/human_agent_assistant_event.py | 69 + .../cloud/dialogflow_v2beta1/types/intent.py | 2124 ++++++++++ .../types/knowledge_base.py | 257 ++ .../dialogflow_v2beta1/types/participant.py | 1473 +++++++ .../cloud/dialogflow_v2beta1/types/session.py | 1151 +++++ .../types/session_entity_type.py | 274 ++ .../types/validation_result.py | 93 + .../cloud/dialogflow_v2beta1/types/version.py | 265 ++ .../cloud/dialogflow_v2beta1/types/webhook.py | 260 ++ owl-bot-staging/v2beta1/mypy.ini | 3 + owl-bot-staging/v2beta1/noxfile.py | 132 + .../fixup_dialogflow_v2beta1_keywords.py | 263 ++ owl-bot-staging/v2beta1/setup.py | 53 + 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 | 3145 ++++++++++++++ .../dialogflow_v2beta1/test_answer_records.py | 1814 ++++++++ .../gapic/dialogflow_v2beta1/test_contexts.py | 2595 ++++++++++++ .../test_conversation_profiles.py | 2459 +++++++++++ .../dialogflow_v2beta1/test_conversations.py | 2848 +++++++++++++ .../dialogflow_v2beta1/test_documents.py | 2804 +++++++++++++ .../dialogflow_v2beta1/test_entity_types.py | 3580 ++++++++++++++++ .../dialogflow_v2beta1/test_environments.py | 2420 +++++++++++ .../dialogflow_v2beta1/test_fulfillments.py | 1487 +++++++ .../gapic/dialogflow_v2beta1/test_intents.py | 3100 ++++++++++++++ .../test_knowledge_bases.py | 2378 +++++++++++ .../dialogflow_v2beta1/test_participants.py | 3710 +++++++++++++++++ .../test_session_entity_types.py | 2369 +++++++++++ .../gapic/dialogflow_v2beta1/test_sessions.py | 1403 +++++++ .../gapic/dialogflow_v2beta1/test_versions.py | 2391 +++++++++++ 380 files changed, 186990 insertions(+) create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/agents.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/documents.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/environments.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/intents.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/participants.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/types.rst create mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/versions.rst create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py create mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py create mode 100644 owl-bot-staging/v2beta1/MANIFEST.in create mode 100644 owl-bot-staging/v2beta1/README.rst create mode 100644 owl-bot-staging/v2beta1/docs/conf.py create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst create mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst create mode 100644 owl-bot-staging/v2beta1/docs/index.rst create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py create mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py create mode 100644 owl-bot-staging/v2beta1/mypy.ini create mode 100644 owl-bot-staging/v2beta1/noxfile.py create mode 100644 owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py create mode 100644 owl-bot-staging/v2beta1/setup.py create mode 100644 owl-bot-staging/v2beta1/tests/__init__.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py create mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 000000000..e6fb0b1cd --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +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 new file mode 100644 index 000000000..6a2fa7289 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +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 new file mode 100644 index 000000000..8b2599a7e --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-dialogflow" +copyright = u"2020, 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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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 new file mode 100644 index 000000000..8661ecd44 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..20345f618 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..ab27d7b1e --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst @@ -0,0 +1,10 @@ +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_profiles.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst new file mode 100644 index 000000000..e5c4cda45 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..a288e3783 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..c95415ace --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..82634156b --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..e0ca6f7f7 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..27f77aa3a --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst @@ -0,0 +1,6 @@ +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 new file mode 100644 index 000000000..8418cb20d --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..7440330af --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..6ce8a2c52 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..8bdbdfe41 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/services.rst @@ -0,0 +1,20 @@ +Services for Google Cloud Dialogflow v2 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/v2/docs/dialogflow_v2/session_entity_types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst new file mode 100644 index 000000000..e1d7bd321 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..1da650e33 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst @@ -0,0 +1,6 @@ +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 new file mode 100644 index 000000000..205c4fadd --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflow v2 API +======================================== + +.. automodule:: google.cloud.dialogflow_v2.types + :members: + :undoc-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 new file mode 100644 index 000000000..af34a4719 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 000000000..79b49743a --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +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 new file mode 100644 index 000000000..641057fda --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from 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_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 VoiceSelectionParams +from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant +from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflow_v2.types.context import Context +from google.cloud.dialogflow_v2.types.context import CreateContextRequest +from google.cloud.dialogflow_v2.types.context import DeleteAllContextsRequest +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_event import ConversationEvent +from google.cloud.dialogflow_v2.types.conversation_profile import AutomatedAgentConfig +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 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 GetDocumentRequest +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.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 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 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 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 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', + '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', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'SuggestionFeature', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'GetDocumentRequest', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AutomatedAgentReply', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'SuggestionResult', + '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/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow/py.typed @@ -0,0 +1,2 @@ +# 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 new file mode 100644 index 000000000..25fc98a76 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py @@ -0,0 +1,420 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .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 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 VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender +from .types.context import Context +from .types.context import CreateContextRequest +from .types.context import DeleteAllContextsRequest +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_event import ConversationEvent +from .types.conversation_profile import AutomatedAgentConfig +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 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 GetDocumentRequest +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.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 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 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 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 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', + 'ConversationProfilesAsyncClient', + 'ConversationsAsyncClient', + 'DocumentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'FulfillmentsAsyncClient', + 'IntentsAsyncClient', + 'KnowledgeBasesAsyncClient', + 'ParticipantsAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'VersionsAsyncClient', +'Agent', +'AgentAssistantFeedback', +'AgentAssistantRecord', +'AgentsClient', +'AnalyzeContentRequest', +'AnalyzeContentResponse', +'AnnotatedMessagePart', +'AnswerFeedback', +'AnswerRecord', +'AnswerRecordsClient', +'ArticleAnswer', +'AudioEncoding', +'AutomatedAgentConfig', +'AutomatedAgentReply', +'BatchCreateEntitiesRequest', +'BatchDeleteEntitiesRequest', +'BatchDeleteEntityTypesRequest', +'BatchDeleteIntentsRequest', +'BatchUpdateEntitiesRequest', +'BatchUpdateEntityTypesRequest', +'BatchUpdateEntityTypesResponse', +'BatchUpdateIntentsRequest', +'BatchUpdateIntentsResponse', +'CompleteConversationRequest', +'Context', +'ContextsClient', +'Conversation', +'ConversationEvent', +'ConversationPhoneNumber', +'ConversationProfile', +'ConversationProfilesClient', +'ConversationsClient', +'CreateContextRequest', +'CreateConversationProfileRequest', +'CreateConversationRequest', +'CreateDocumentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateIntentRequest', +'CreateKnowledgeBaseRequest', +'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', +'FaqAnswer', +'Fulfillment', +'FulfillmentsClient', +'GetAgentRequest', +'GetContextRequest', +'GetConversationProfileRequest', +'GetConversationRequest', +'GetDocumentRequest', +'GetEntityTypeRequest', +'GetEnvironmentHistoryRequest', +'GetEnvironmentRequest', +'GetFulfillmentRequest', +'GetIntentRequest', +'GetKnowledgeBaseRequest', +'GetParticipantRequest', +'GetSessionEntityTypeRequest', +'GetValidationResultRequest', +'GetVersionRequest', +'HumanAgentAssistantConfig', +'HumanAgentAssistantEvent', +'HumanAgentHandoffConfig', +'ImportAgentRequest', +'InputAudioConfig', +'Intent', +'IntentBatch', +'IntentView', +'IntentsClient', +'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', +'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', +'SpeechContext', +'SpeechModelVariant', +'SpeechToTextConfig', +'SpeechWordInfo', +'SsmlVoiceGender', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SuggestArticlesRequest', +'SuggestArticlesResponse', +'SuggestFaqAnswersRequest', +'SuggestFaqAnswersResponse', +'SuggestionFeature', +'SuggestionResult', +'SynthesizeSpeechConfig', +'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/v2/google/cloud/dialogflow_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json new file mode 100644 index 000000000..b73c53792 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json @@ -0,0 +1,1039 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2", + "protoPackage": "google.cloud.dialogflow.v2", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed @@ -0,0 +1,2 @@ +# 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 new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/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 new file mode 100644 index 000000000..057c8b80b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..f4b5b9026 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py @@ -0,0 +1,922 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AgentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: agent.GetAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_agent.SetAgentRequest = None, + *, + agent: gcd_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.SetAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: agent.DeleteAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.SearchAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.SearchAgentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.TrainAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.TrainAgentRequest`): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.ExportAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified agent to a ZIP file. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ExportAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.ImportAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ImportAgentRequest`): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.RestoreAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.RestoreAgentRequest`): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.GetValidationResultRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetValidationResultRequest`): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..a0da3d0e7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py @@ -0,0 +1,1112 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AgentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AgentsTransport): + # transport is a AgentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_agent(self, + request: agent.GetAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.GetAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_agent.SetAgentRequest = None, + *, + agent: gcd_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.SetAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: agent.DeleteAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.SearchAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (google.cloud.dialogflow_v2.types.SearchAgentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.TrainAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.TrainAgentRequest): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.ExportAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified agent to a ZIP file. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.ExportAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.ImportAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (google.cloud.dialogflow_v2.types.ImportAgentRequest): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.RestoreAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (google.cloud.dialogflow_v2.types.RestoreAgentRequest): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.GetValidationResultRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.GetValidationResultRequest): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..5ef3d2074 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..0dc0c06c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AgentsTransport +from .grpc import AgentsGrpcTransport +from .grpc_asyncio import AgentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] +_transport_registry['grpc'] = AgentsGrpcTransport +_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport + +__all__ = ( + 'AgentsTransport', + 'AgentsGrpcTransport', + 'AgentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..6185b62fe --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..7890e85fc --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py @@ -0,0 +1,522 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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'] + + +__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 new file mode 100644 index 000000000..beedb258f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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'] + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..16c67859b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..33c4bc1a1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", + client_options: 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: answer_record.ListAnswerRecordsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsAsyncPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_answer_record.UpdateAnswerRecordRequest = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..8b4317a5b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py @@ -0,0 +1,557 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnswerRecordsGrpcTransport +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AnswerRecordsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AnswerRecordsTransport): + # transport is a AnswerRecordsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_answer_records(self, + request: answer_record.ListAnswerRecordsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_answer_record.UpdateAnswerRecordRequest = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..1e86c11ca --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..99c08cf37 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AnswerRecordsTransport +from .grpc import AnswerRecordsGrpcTransport +from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] +_transport_registry['grpc'] = AnswerRecordsGrpcTransport +_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport + +__all__ = ( + 'AnswerRecordsTransport', + 'AnswerRecordsGrpcTransport', + 'AnswerRecordsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..238ccec6d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..13aaaa972 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..1e168c246 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .grpc import AnswerRecordsGrpcTransport + + +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'AnswerRecordsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..b0d60f297 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..476b7c3e4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ContextsTransport] = "grpc_asyncio", + client_options: 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: context.ListContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsAsyncPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListContextsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: context.GetContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_context.CreateContextRequest = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: context.DeleteContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: context.DeleteAllContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteAllContextsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..7081d027b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py @@ -0,0 +1,890 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import field_mask_pb2 # 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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ContextsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ContextsTransport): + # transport is a ContextsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_contexts(self, + request: context.ListContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (google.cloud.dialogflow_v2.types.ListContextsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: context.GetContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (google.cloud.dialogflow_v2.types.GetContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_context.CreateContextRequest = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (google.cloud.dialogflow_v2.types.CreateContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: context.DeleteContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: context.DeleteAllContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteAllContextsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..8b13d41ab --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..eb854f545 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ContextsTransport +from .grpc import ContextsGrpcTransport +from .grpc_asyncio import ContextsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] +_transport_registry['grpc'] = ContextsGrpcTransport +_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport + +__all__ = ( + 'ContextsTransport', + 'ContextsGrpcTransport', + 'ContextsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..e9533fa3e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..8884de505 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..d258d4aaf --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py @@ -0,0 +1,387 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'ContextsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..3e8e4ea19 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..c2c835023 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.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.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) + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", + client_options: 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: conversation_profile.ListConversationProfilesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesAsyncPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListConversationProfilesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation_profile.GetConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_conversation_profile.CreateConversationProfileRequest = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..dba48424b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py @@ -0,0 +1,817 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.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.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 + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationProfilesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationProfilesTransport): + # transport is a ConversationProfilesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_conversation_profiles(self, + request: conversation_profile.ListConversationProfilesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (google.cloud.dialogflow_v2.types.ListConversationProfilesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation_profile.GetConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (google.cloud.dialogflow_v2.types.GetConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_conversation_profile.CreateConversationProfileRequest = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.CreateConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (google.cloud.dialogflow_v2.types.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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..65ef11f7a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..19a679f49 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationProfilesTransport +from .grpc import ConversationProfilesGrpcTransport +from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] +_transport_registry['grpc'] = ConversationProfilesGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport + +__all__ = ( + 'ConversationProfilesTransport', + 'ConversationProfilesGrpcTransport', + 'ConversationProfilesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..f280996cf --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..0f8cc8e8e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..02088afc8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'ConversationProfilesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..0445da9c4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..872f9d3bb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py @@ -0,0 +1,625 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.protobuf import timestamp_pb2 # 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 + + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ConversationsTransport] = "grpc_asyncio", + client_options: 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: gcd_conversation.CreateConversationRequest = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListConversationsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.GetConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.CompleteConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CompleteConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.ListMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListMessagesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..80ec8e11e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py @@ -0,0 +1,830 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationsGrpcTransport +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationsTransport): + # transport is a ConversationsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_conversation(self, + request: gcd_conversation.CreateConversationRequest = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.CreateConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (google.cloud.dialogflow_v2.types.ListConversationsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.GetConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (google.cloud.dialogflow_v2.types.GetConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.CompleteConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (google.cloud.dialogflow_v2.types.CompleteConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.ListMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.ListMessagesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..b102ea98e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..9d9ee9030 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationsTransport +from .grpc import ConversationsGrpcTransport +from .grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] +_transport_registry['grpc'] = ConversationsGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport + +__all__ = ( + 'ConversationsTransport', + 'ConversationsGrpcTransport', + 'ConversationsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..db30b0301 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..42e3f8764 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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'] + + +__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 new file mode 100644 index 000000000..06141f8fd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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'] + + +__all__ = ( + 'ConversationsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..cee70ad81 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..4748c2c80 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py @@ -0,0 +1,773 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, DocumentsTransport] = "grpc_asyncio", + client_options: 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: document.ListDocumentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Returns the list of all documents of the knowledge + base. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListDocumentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: document.GetDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_document.CreateDocumentRequest = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new document. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 delete_document(self, + request: document.DeleteDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified document. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteDocumentRequest`): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_document.UpdateDocumentRequest = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified document. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: document.ReloadDocumentRequest = None, + *, + name: str = None, + content_uri: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ReloadDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..914f8bbab --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py @@ -0,0 +1,960 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentsTransport): + # transport is a DocumentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_documents(self, + request: document.ListDocumentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Returns the list of all documents of the knowledge + base. + + Args: + request (google.cloud.dialogflow_v2.types.ListDocumentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: document.GetDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Args: + request (google.cloud.dialogflow_v2.types.GetDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_document.CreateDocumentRequest = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new document. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.CreateDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 delete_document(self, + request: document.DeleteDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified document. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.DeleteDocumentRequest): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_document.UpdateDocumentRequest = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the specified document. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.UpdateDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: document.ReloadDocumentRequest = None, + *, + name: str = None, + content_uri: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.ReloadDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..1d2c160be --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..f9ae67be5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentsTransport +from .grpc import DocumentsGrpcTransport +from .grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] +_transport_registry['grpc'] = DocumentsGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport + +__all__ = ( + 'DocumentsTransport', + 'DocumentsGrpcTransport', + 'DocumentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..a29fbca95 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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.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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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 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() + + +__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 new file mode 100644 index 000000000..6738b9bf5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + Operation + + 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 delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete document method over gRPC. + + Deletes the specified document. + + Operation + + 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. + + Operation + + 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. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Operation + + 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'] + + +__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 new file mode 100644 index 000000000..d74d21a45 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + Operation + + 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 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. + + Operation + + 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. + + Operation + + 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. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Operation + + 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'] + + +__all__ = ( + 'DocumentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..82dfe86fd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..872034477 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py @@ -0,0 +1,1195 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, EntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: entity_type.ListEntityTypesRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesAsyncPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListEntityTypesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: entity_type.BatchUpdateEntityTypesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple entity types in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest`): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: entity_type.BatchDeleteEntityTypesRequest = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entity types in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates multiple new entities in the specified entity type. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entities in the specified entity type. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..4b0947dcf --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py @@ -0,0 +1,1383 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EntityTypesTransport): + # transport is a EntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_entity_types(self, + request: entity_type.ListEntityTypesRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListEntityTypesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (google.cloud.dialogflow_v2.types.GetEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.CreateEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: entity_type.BatchUpdateEntityTypesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple entity types in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: entity_type.BatchDeleteEntityTypesRequest = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entity types in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates multiple new entities in the specified entity type. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entities in the specified entity type. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..2e03a613e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..1a2aa82dc --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EntityTypesTransport +from .grpc import EntityTypesGrpcTransport +from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] +_transport_registry['grpc'] = EntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'EntityTypesTransport', + 'EntityTypesGrpcTransport', + 'EntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..d6012fae0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..50e9c62bb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py @@ -0,0 +1,522 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__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 new file mode 100644 index 000000000..cdc5c9abe --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..a3ad29ecd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..c3d227664 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py @@ -0,0 +1,607 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +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) + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: environment.ListEnvironmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsAsyncPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListEnvironmentsRequest`): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.ListEnvironmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + 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: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_environment(self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_environment_history(self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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 new file mode 100644 index 000000000..ea085afd9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py @@ -0,0 +1,808 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_environments(self, + request: environment.ListEnvironmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListEnvironmentsRequest): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (str): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.ListEnvironmentsRequest. + # 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: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_environment(self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_environment_history(self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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 new file mode 100644 index 000000000..a9efd221e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 new file mode 100644 index 000000000..fac90efe0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..945470a49 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import environment +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_environments(self) -> 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() + + +__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 new file mode 100644 index 000000000..d7a329652 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py @@ -0,0 +1,393 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import environment +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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.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 keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + environment.EnvironmentHistory]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/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 new file mode 100644 index 000000000..4a2617127 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,397 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import environment +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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.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 keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory]]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..95fd359ef --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', +) diff --git a/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 new file mode 100644 index 000000000..dff171a22 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py @@ -0,0 +1,345 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod(FulfillmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FulfillmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(FulfillmentsClient.parse_common_organization_path) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod(FulfillmentsClient.parse_common_project_path) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod(FulfillmentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """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: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetFulfillmentRequest`): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = fulfillment.GetFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_fulfillment(self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest`): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsAsyncClient", +) diff --git a/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 new file mode 100644 index 000000000..e0e36ef7a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py @@ -0,0 +1,532 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FulfillmentsTransport]: + """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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_fulfillment(self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (google.cloud.dialogflow_v2.types.GetFulfillmentRequest): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_fulfillment(self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsClient", +) diff --git a/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 new file mode 100644 index 000000000..4b41f9212 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry['grpc'] = FulfillmentsGrpcTransport +_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + 'FulfillmentsTransport', + 'FulfillmentsGrpcTransport', + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..5ffb71f97 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, + default_timeout=None, + client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[ + fulfillment.Fulfillment, + Awaitable[fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[ + gcd_fulfillment.Fulfillment, + Awaitable[gcd_fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FulfillmentsTransport', +) diff --git a/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 new file mode 100644 index 000000000..6330ba94a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + gcd_fulfillment.Fulfillment]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + +__all__ = ( + 'FulfillmentsGrpcTransport', +) diff --git a/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 new file mode 100644 index 000000000..6a7c6562d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Awaitable[fulfillment.Fulfillment]]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment]]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + +__all__ = ( + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..8204500fb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..bf8a73421 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py @@ -0,0 +1,871 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, IntentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: intent.ListIntentsRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsAsyncPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListIntentsRequest`): + 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``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, + *, + intent: gcd_intent.Intent = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: intent.DeleteIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or + indirect followup intents. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: intent.BatchUpdateIntentsRequest = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple intents in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes intents in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..cff8eaaa3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py @@ -0,0 +1,1067 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, IntentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, IntentsTransport): + # transport is a IntentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_intents(self, + request: intent.ListIntentsRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListIntentsRequest): + 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``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (google.cloud.dialogflow_v2.types.GetIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.CreateIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, + *, + intent: gcd_intent.Intent = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: intent.DeleteIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or + indirect followup intents. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: intent.BatchUpdateIntentsRequest = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple intents in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes intents in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..cdb3d2195 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..aa8039bba --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import IntentsTransport +from .grpc import IntentsGrpcTransport +from .grpc_asyncio import IntentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] +_transport_registry['grpc'] = IntentsGrpcTransport +_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport + +__all__ = ( + 'IntentsTransport', + 'IntentsGrpcTransport', + 'IntentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..980268863 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..ea2071352 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py @@ -0,0 +1,433 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__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 new file mode 100644 index 000000000..e3ef04fd5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..670d8e66d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..686912fe9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py @@ -0,0 +1,601 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", + client_options: 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: knowledge_base.ListKnowledgeBasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesAsyncPager: + r"""Returns the list of all knowledge bases of the + specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: knowledge_base.GetKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..2a303b953 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py @@ -0,0 +1,788 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KnowledgeBasesGrpcTransport +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, KnowledgeBasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, KnowledgeBasesTransport): + # transport is a KnowledgeBasesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_knowledge_bases(self, + request: knowledge_base.ListKnowledgeBasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesPager: + r"""Returns the list of all knowledge bases of the + specified agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: knowledge_base.GetKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Args: + request (google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Args: + request (google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..479130853 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..c04ef7c9f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import KnowledgeBasesTransport +from .grpc import KnowledgeBasesGrpcTransport +from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] +_transport_registry['grpc'] = KnowledgeBasesGrpcTransport +_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport + +__all__ = ( + 'KnowledgeBasesTransport', + 'KnowledgeBasesGrpcTransport', + 'KnowledgeBasesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..d50f63144 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..3872d90fa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..270cf1ffa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py @@ -0,0 +1,360 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'KnowledgeBasesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..376e9e7d4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..aa70ac524 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -0,0 +1,766 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from google.cloud.dialogflow_v2.types import session +from google.protobuf import field_mask_pb2 # 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 + + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ParticipantsTransport] = "grpc_asyncio", + client_options: 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: gcd_participant.CreateParticipantRequest = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.ListParticipantsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsAsyncPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListParticipantsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_participant.UpdateParticipantRequest = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.AnalyzeContentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + async def suggest_articles(self, + request: participant.SuggestArticlesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on + specific historical messages. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.SuggestArticlesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.SuggestFaqAnswersRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..826119b07 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py @@ -0,0 +1,983 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from google.cloud.dialogflow_v2.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ParticipantsGrpcTransport +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ParticipantsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ParticipantsTransport): + # transport is a ParticipantsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_participant(self, + request: gcd_participant.CreateParticipantRequest = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (google.cloud.dialogflow_v2.types.CreateParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (google.cloud.dialogflow_v2.types.GetParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.ListParticipantsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (google.cloud.dialogflow_v2.types.ListParticipantsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_participant.UpdateParticipantRequest = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (google.cloud.dialogflow_v2.types.AnalyzeContentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 suggest_articles(self, + request: participant.SuggestArticlesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on + specific historical messages. + + Args: + request (google.cloud.dialogflow_v2.types.SuggestArticlesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.SuggestFaqAnswersRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..f4bea5ed9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..e30c79b00 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ParticipantsTransport +from .grpc import ParticipantsGrpcTransport +from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] +_transport_registry['grpc'] = ParticipantsGrpcTransport +_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport + +__all__ = ( + 'ParticipantsTransport', + 'ParticipantsGrpcTransport', + 'ParticipantsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..15cd248da --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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, + ), + } + + @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 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() + + +__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 new file mode 100644 index 000000000..645ac0c78 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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 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'] + + +__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 new file mode 100644 index 000000000..f963f52d9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py @@ -0,0 +1,418 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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'] + + +__all__ = ( + 'ParticipantsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..fb6678b14 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..f393102a1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py @@ -0,0 +1,629 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: session_entity_type.ListSessionEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: session_entity_type.GetSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..a74bf29b6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py @@ -0,0 +1,816 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionEntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionEntityTypesTransport): + # transport is a SessionEntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_session_entity_types(self, + request: session_entity_type.ListSessionEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: session_entity_type.GetSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..df1a4f275 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..fee526724 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionEntityTypesTransport +from .grpc import SessionEntityTypesGrpcTransport +from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] +_transport_registry['grpc'] = SessionEntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'SessionEntityTypesTransport', + 'SessionEntityTypesGrpcTransport', + 'SessionEntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..704dae441 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..d367539aa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..f38327593 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'SessionEntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..92490cc5a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..b2239cea8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py @@ -0,0 +1,396 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.rpc import status_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, SessionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: gcd_session.DetectIntentRequest = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DetectIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: AsyncIterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + 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 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. 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..e325e64ab --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionsTransport): + # transport is a SessionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def detect_intent(self, + request: gcd_session.DetectIntentRequest = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (google.cloud.dialogflow_v2.types.DetectIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: Iterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + 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 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. 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..fde19f616 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionsTransport +from .grpc import SessionsGrpcTransport +from .grpc_asyncio import SessionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] +_transport_registry['grpc'] = SessionsGrpcTransport +_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport + +__all__ = ( + 'SessionsTransport', + 'SessionsGrpcTransport', + 'SessionsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..74789f356 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..0821b615a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py @@ -0,0 +1,292 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + + 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). + + 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'] + + +__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 new file mode 100644 index 000000000..c7b313261 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + + 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). + + 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'] + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..630246bde --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/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 new file mode 100644 index 000000000..68b1a8aea --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py @@ -0,0 +1,639 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + version_path = staticmethod(VersionsClient.version_path) + parse_version_path = staticmethod(VersionsClient.parse_version_path) + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """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: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.ListVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.GetVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.DeleteVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/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 new file mode 100644 index 000000000..ff73df380 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py @@ -0,0 +1,826 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_versions(self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.ListVersionsRequest): + request = version.ListVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (google.cloud.dialogflow_v2.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.GetVersionRequest): + request = version.GetVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (google.cloud.dialogflow_v2.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.DeleteVersionRequest): + request = version.DeleteVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/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 new file mode 100644 index 000000000..bead6290c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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) -> AsyncIterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 new file mode 100644 index 000000000..dfb70ce95 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..8e207d9aa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Union[ + version.ListVersionsResponse, + Awaitable[version.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/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 new file mode 100644 index 000000000..5294fdbd8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/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 new file mode 100644 index 000000000..74847abc3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,365 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Awaitable[version.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py new file mode 100644 index 000000000..3656d3519 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .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, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, +) +from .context import ( + Context, + CreateContextRequest, + DeleteAllContextsRequest, + DeleteContextRequest, + GetContextRequest, + ListContextsRequest, + ListContextsResponse, + UpdateContextRequest, +) +from .conversation import ( + CompleteConversationRequest, + Conversation, + ConversationPhoneNumber, + CreateConversationRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + ListMessagesRequest, + ListMessagesResponse, +) +from .conversation_event import ( + ConversationEvent, +) +from .conversation_profile import ( + AutomatedAgentConfig, + ConversationProfile, + CreateConversationProfileRequest, + DeleteConversationProfileRequest, + GetConversationProfileRequest, + HumanAgentAssistantConfig, + HumanAgentHandoffConfig, + ListConversationProfilesRequest, + ListConversationProfilesResponse, + LoggingConfig, + NotificationConfig, + SuggestionFeature, + UpdateConversationProfileRequest, +) +from .document import ( + CreateDocumentRequest, + DeleteDocumentRequest, + Document, + GetDocumentRequest, + 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 .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, + AutomatedAgentReply, + CreateParticipantRequest, + DtmfParameters, + FaqAnswer, + GetParticipantRequest, + ListParticipantsRequest, + ListParticipantsResponse, + Message, + MessageAnnotation, + OutputAudio, + Participant, + SuggestArticlesRequest, + SuggestArticlesResponse, + SuggestFaqAnswersRequest, + SuggestFaqAnswersResponse, + SuggestionResult, + 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', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'SuggestionFeature', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'GetDocumentRequest', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AutomatedAgentReply', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'SuggestionResult', + '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 new file mode 100644 index 000000000..736fe28e5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + '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 (Sequence[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. + """ + MATCH_MODE_UNSPECIFIED = 0 + MATCH_MODE_HYBRID = 1 + MATCH_MODE_ML_ONLY = 2 + + class ApiVersion(proto.Enum): + r"""API version for the agent.""" + 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.""" + TIER_UNSPECIFIED = 0 + TIER_STANDARD = 1 + TIER_ENTERPRISE = 2 + TIER_ENTERPRISE_PLUS = 3 + + parent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + enable_logging = proto.Field( + proto.BOOL, + number=8, + ) + match_mode = proto.Field( + proto.ENUM, + number=9, + enum=MatchMode, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=10, + ) + api_version = proto.Field( + proto.ENUM, + number=14, + enum=ApiVersion, + ) + tier = proto.Field( + proto.ENUM, + number=15, + enum=Tier, + ) + + +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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Agent', + ) + update_mask = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchAgentsResponse(proto.Message): + r"""The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + + Attributes: + agents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Agent', + ) + next_page_token = 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 = 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + + 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``. + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class ImportAgentRequest(proto.Message): + r"""The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + + 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://". + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + + 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://". + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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 new file mode 100644 index 000000000..9eaf196f5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py @@ -0,0 +1,350 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + answer_feedback = proto.Field( + proto.MESSAGE, + number=2, + message='AnswerFeedback', + ) + agent_assistant_record = proto.Field( + proto.MESSAGE, + number=4, + oneof='record', + message='AgentAssistantRecord', + ) + + +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): + Required. Filters to restrict results to specific answer + records. Filter on answer record type. Currently predicates + on ``type`` is supported, valid values are + ``ARTICLE_ANSWER``, ``FAQ_ANSWER``. + + 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 = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnswerRecordsResponse(proto.Message): + r"""Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + + Attributes: + answer_records (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + next_page_token = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + update_mask = 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. + + 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. + 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.""" + CORRECTNESS_LEVEL_UNSPECIFIED = 0 + NOT_CORRECT = 1 + PARTIALLY_CORRECT = 2 + FULLY_CORRECT = 3 + + correctness_level = proto.Field( + proto.ENUM, + number=1, + enum=CorrectnessLevel, + ) + agent_assistant_detail_feedback = proto.Field( + proto.MESSAGE, + number=2, + oneof='detail_feedback', + message='AgentAssistantFeedback', + ) + clicked = proto.Field( + proto.BOOL, + number=3, + ) + click_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + displayed = proto.Field( + proto.BOOL, + number=4, + ) + display_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class AgentAssistantFeedback(proto.Message): + r"""Detail feedback of Agent Assist result. + Attributes: + answer_relevance (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.AnswerRelevance): + Optional. Whether or not the suggested answer is relevant. + + 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]. + """ + class AnswerRelevance(proto.Enum): + r"""Relevance of an answer.""" + ANSWER_RELEVANCE_UNSPECIFIED = 0 + IRRELEVANT = 1 + RELEVANT = 2 + + class DocumentCorrectness(proto.Enum): + r"""Correctness of document.""" + DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 + INCORRECT = 1 + CORRECT = 2 + + class DocumentEfficiency(proto.Enum): + r"""Efficiency of document.""" + DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 + INEFFICIENT = 1 + EFFICIENT = 2 + + answer_relevance = proto.Field( + proto.ENUM, + number=1, + enum=AnswerRelevance, + ) + document_correctness = proto.Field( + proto.ENUM, + number=2, + enum=DocumentCorrectness, + ) + document_efficiency = proto.Field( + proto.ENUM, + number=3, + enum=DocumentEfficiency, + ) + + +class AgentAssistantRecord(proto.Message): + r"""Represents a record of a human agent assist answer. + Attributes: + article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): + Output only. The article suggestion answer. + faq_answer (google.cloud.dialogflow_v2.types.FaqAnswer): + Output only. The FAQ answer. + """ + + article_suggestion_answer = proto.Field( + proto.MESSAGE, + number=5, + oneof='answer', + message=participant.ArticleAnswer, + ) + faq_answer = proto.Field( + proto.MESSAGE, + number=6, + oneof='answer', + message=participant.FaqAnswer, + ) + + +__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 new file mode 100644 index 000000000..719655107 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'SpeechContext', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + '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. + """ + 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. + """ + 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 `__. + """ + 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.""" + 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 SpeechContext(proto.Message): + r"""Hints for the speech recognizer to help with recognition in a + specific conversation state. + + Attributes: + phrases (Sequence[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 = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + +class SpeechWordInfo(proto.Message): + r"""Information for a word recognized by the speech recognizer. + Attributes: + word (str): + The word this info is for. + 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 = proto.Field( + proto.STRING, + number=3, + ) + start_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class InputAudioConfig(proto.Message): + 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 (Sequence[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 (Sequence[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 = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechContext', + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + disable_no_speech_recognized_event = proto.Field( + proto.BOOL, + number=14, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + ssml_gender = proto.Field( + proto.ENUM, + number=2, + enum='SsmlVoiceGender', + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration of how speech should be synthesized. + Attributes: + speaking_rate (float): + Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 + 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 (Sequence[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 = proto.Field( + proto.DOUBLE, + number=1, + ) + pitch = proto.Field( + proto.DOUBLE, + number=2, + ) + volume_gain_db = proto.Field( + proto.DOUBLE, + number=3, + ) + effects_profile_id = proto.RepeatedField( + proto.STRING, + number=5, + ) + voice = proto.Field( + proto.MESSAGE, + number=4, + message='VoiceSelectionParams', + ) + + +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 = proto.Field( + proto.ENUM, + number=1, + enum='OutputAudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + synthesize_speech_config = proto.Field( + proto.MESSAGE, + number=3, + message='SynthesizeSpeechConfig', + ) + + +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): + Optional. 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. + """ + + speech_model_variant = proto.Field( + proto.ENUM, + number=1, + enum='SpeechModelVariant', + ) + + +__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 new file mode 100644 index 000000000..066ef0f13 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import 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 = proto.Field( + proto.STRING, + number=1, + ) + lifespan_count = proto.Field( + proto.INT32, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ListContextsRequest(proto.Message): + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListContextsResponse(proto.Message): + r"""The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + + Attributes: + contexts (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Context', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Context', + ) + update_mask = 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 = 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 = 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 new file mode 100644 index 000000000..30727db67 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py @@ -0,0 +1,390 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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', + }, +) + + +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.""" + 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 + """ + CONVERSATION_STAGE_UNSPECIFIED = 0 + VIRTUAL_AGENT_STAGE = 1 + HUMAN_ASSIST_STAGE = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + lifecycle_state = proto.Field( + proto.ENUM, + number=2, + enum=LifecycleState, + ) + conversation_profile = proto.Field( + proto.STRING, + number=3, + ) + phone_number = proto.Field( + proto.MESSAGE, + number=4, + message='ConversationPhoneNumber', + ) + start_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + conversation_stage = proto.Field( + proto.ENUM, + number=7, + enum=ConversationStage, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + conversation = proto.Field( + proto.MESSAGE, + number=2, + message='Conversation', + ) + conversation_id = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListConversationsResponse(proto.Message): + r"""The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + + Attributes: + conversations (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Conversation', + ) + next_page_token = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessagesResponse(proto.Message): + r"""The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + + Attributes: + messages (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=participant.Message, + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=3, + ) + + +__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 new file mode 100644 index 000000000..19e056323 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + + 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. + """ + class Type(proto.Enum): + r"""Enumeration of the types of events available.""" + TYPE_UNSPECIFIED = 0 + CONVERSATION_STARTED = 1 + CONVERSATION_FINISHED = 2 + HUMAN_INTERVENTION_NEEDED = 3 + NEW_MESSAGE = 5 + UNRECOVERABLE_ERROR = 4 + + conversation = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + error_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + new_message_payload = 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_profile.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py new file mode 100644 index 000000000..5c9e5faab --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py @@ -0,0 +1,834 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import audio_config +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', + }, +) + + +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 which represents the + conversationProfile. If unspecified, the default + language code en-us applies. Users need to + create a ConversationProfile for each language + they want to support. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + automated_agent_config = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentConfig', + ) + human_agent_assistant_config = proto.Field( + proto.MESSAGE, + number=4, + message='HumanAgentAssistantConfig', + ) + human_agent_handoff_config = proto.Field( + proto.MESSAGE, + number=5, + message='HumanAgentHandoffConfig', + ) + notification_config = proto.Field( + proto.MESSAGE, + number=6, + message='NotificationConfig', + ) + logging_config = proto.Field( + proto.MESSAGE, + number=7, + message='LoggingConfig', + ) + new_message_event_notification_config = proto.Field( + proto.MESSAGE, + number=8, + message='NotificationConfig', + ) + stt_config = proto.Field( + proto.MESSAGE, + number=9, + message=audio_config.SpeechToTextConfig, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationProfilesResponse(proto.Message): + r"""The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + + Attributes: + conversation_profiles (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + conversation_profile = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + update_mask = 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 = 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. + + Format: + ``projects//locations//agent/environments/``. + If environment is not specified, the default ``draft`` + environment is used. Refer to + `DetectIntentRequest `__ + for more details. + """ + + agent = proto.Field( + proto.STRING, + number=1, + ) + + +class HumanAgentAssistantConfig(proto.Message): + r"""Defines the Human Agent Assist to connect to a conversation. + Attributes: + notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): + Pub/Sub topic on which to publish new agent + 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 = proto.Field( + proto.BOOL, + number=1, + ) + only_end_user = proto.Field( + proto.BOOL, + number=2, + ) + + class SuggestionFeatureConfig(proto.Message): + r"""Config for suggestion features. + Attributes: + suggestion_feature (google.cloud.dialogflow_v2.types.SuggestionFeature): + The suggestion feature. + 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. + """ + + suggestion_feature = proto.Field( + proto.MESSAGE, + number=5, + message='SuggestionFeature', + ) + enable_event_based_suggestion = proto.Field( + proto.BOOL, + number=3, + ) + suggestion_trigger_settings = proto.Field( + proto.MESSAGE, + number=10, + message='HumanAgentAssistantConfig.SuggestionTriggerSettings', + ) + query_config = proto.Field( + proto.MESSAGE, + number=6, + message='HumanAgentAssistantConfig.SuggestionQueryConfig', + ) + conversation_model_config = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.ConversationModelConfig', + ) + + class SuggestionConfig(proto.Message): + r"""Detail human agent assistant config. + Attributes: + feature_configs (Sequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): + Configuration of different suggestion + 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 = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='HumanAgentAssistantConfig.SuggestionFeatureConfig', + ) + group_suggestion_responses = proto.Field( + proto.BOOL, + number=3, + ) + + class SuggestionQueryConfig(proto.Message): + r"""Config for suggestion query. + Attributes: + knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): + Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, + FAQ. + document_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): + Query from knowledge base document. It is used by: + SMART_REPLY, SMART_COMPOSE. + dialogflow_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): + Query from Dialogflow agent. It is used by + DIALOGFLOW_ASSIST. + 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. + 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 (Sequence[str]): + Required. Knowledge bases to query. Format: + ``projects//locations//knowledgeBases/``. + Currently, at most 5 knowledge bases are supported. + """ + + knowledge_bases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DocumentQuerySource(proto.Message): + r"""Document source settings. + + Supported features: SMART_REPLY, SMART_COMPOSE. + + Attributes: + documents (Sequence[str]): + Required. Knowledge documents to query from. Format: + ``projects//locations//knowledgeBases//documents/``. + Currently, at most 5 documents are supported. + """ + + documents = 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 = 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 = proto.Field( + proto.BOOL, + number=1, + ) + drop_virtual_agent_messages = proto.Field( + proto.BOOL, + number=2, + ) + drop_ivr_messages = proto.Field( + proto.BOOL, + number=3, + ) + + knowledge_base_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', + ) + document_query_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', + ) + dialogflow_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', + ) + max_results = proto.Field( + proto.INT32, + number=4, + ) + confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + context_filter_settings = 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. + + Attributes: + model (str): + Conversation model resource name. Format: + ``projects//conversationModels/``. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + 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 = proto.Field( + proto.BOOL, + number=2, + ) + enable_sentiment_analysis = proto.Field( + proto.BOOL, + number=3, + ) + + notification_config = proto.Field( + proto.MESSAGE, + number=2, + message='NotificationConfig', + ) + human_agent_suggestion_config = proto.Field( + proto.MESSAGE, + number=3, + message=SuggestionConfig, + ) + end_user_suggestion_config = proto.Field( + proto.MESSAGE, + number=4, + message=SuggestionConfig, + ) + message_analysis_config = proto.Field( + proto.MESSAGE, + number=5, + message=MessageAnalysisConfig, + ) + + +class HumanAgentHandoffConfig(proto.Message): + r"""Defines the hand off to a live agent, typically on which + external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. + + Attributes: + live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): + Uses LivePerson (https://www.liveperson.com). + salesforce_live_agent_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): + Uses Salesforce Live Agent. + """ + + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + deployment_id = proto.Field( + proto.STRING, + number=2, + ) + button_id = proto.Field( + proto.STRING, + number=3, + ) + endpoint_domain = proto.Field( + proto.STRING, + number=4, + ) + + live_person_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='agent_service', + message=LivePersonConfig, + ) + salesforce_live_agent_config = proto.Field( + proto.MESSAGE, + number=2, + 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. + + Notification works for phone calls, if this topic either 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. + + 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.""" + MESSAGE_FORMAT_UNSPECIFIED = 0 + PROTO = 1 + JSON = 2 + + topic = proto.Field( + proto.STRING, + number=1, + ) + message_format = proto.Field( + proto.ENUM, + number=2, + enum=MessageFormat, + ) + + +class LoggingConfig(proto.Message): + r"""Defines logging behavior for conversation lifecycle events. + Attributes: + enable_stackdriver_logging (bool): + Whether to log conversation events like + [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 = 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.""" + TYPE_UNSPECIFIED = 0 + ARTICLE_SUGGESTION = 1 + FAQ = 2 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + + +__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 new file mode 100644 index 000000000..b10de177b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Document', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'UpdateDocumentRequest', + 'ReloadDocumentRequest', + '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``. + + 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 (Sequence[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. + raw_content (bytes): + The raw content of the document. This field is only + permitted for EXTRACTIVE_QA and FAQ knowledge types. + 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 (Sequence[google.cloud.dialogflow_v2.types.Document.MetadataEntry]): + 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. + """ + class KnowledgeType(proto.Enum): + r"""The knowledge type of document content.""" + KNOWLEDGE_TYPE_UNSPECIFIED = 0 + FAQ = 1 + EXTRACTIVE_QA = 2 + ARTICLE_SUGGESTION = 3 + + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=4, + enum=KnowledgeType, + ) + content_uri = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + raw_content = proto.Field( + proto.BYTES, + number=9, + oneof='source', + ) + enable_auto_reload = proto.Field( + proto.BOOL, + number=11, + ) + latest_reload_status = proto.Field( + proto.MESSAGE, + number=12, + message=ReloadStatus, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +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 = 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + + Attributes: + documents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message='Document', + ) + + +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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document', + ) + update_mask = 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]. + + 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:///``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + content_uri = proto.Field( + proto.STRING, + number=3, + oneof='source', + ) + + +class KnowledgeOperationMetadata(proto.Message): + r"""Metadata in google::longrunning::Operation for Knowledge + operations. + + Attributes: + state (google.cloud.dialogflow_v2.types.KnowledgeOperationMetadata.State): + Output only. The current state of this + operation. + """ + class State(proto.Enum): + r"""States of the operation.""" + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + DONE = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + + +__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 new file mode 100644 index 000000000..1113deb6d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py @@ -0,0 +1,561 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + '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 (Sequence[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.""" + 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). + """ + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Entity, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='EntityType', + ) + language_code = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_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 = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + 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://". + entity_type_batch_inline (google.cloud.dialogflow_v2.types.EntityTypeBatch): + The collection of entity types 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='entity_type_batch', + ) + entity_type_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='entity_type_batch', + message='EntityTypeBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): + The collection of updated or created entity + types. + """ + + entity_types = 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 (Sequence[str]): + Required. The names entity types to delete. All names must + point to the same agent as ``parent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_names = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entity_values = proto.RepeatedField( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class EntityTypeBatch(proto.Message): + r"""This message is a wrapper around a collection of entity + types. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): + A collection of entity types. + """ + + entity_types = 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 new file mode 100644 index 000000000..b6f0292e9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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/`` + 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. + """ + STATE_UNSPECIFIED = 0 + STOPPED = 1 + LOADING = 2 + RUNNING = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + agent_version = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + text_to_speech_settings = proto.Field( + proto.MESSAGE, + number=7, + message='TextToSpeechSettings', + ) + fulfillment = proto.Field( + proto.MESSAGE, + number=8, + message=gcd_fulfillment.Fulfillment, + ) + + +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 (Sequence[google.cloud.dialogflow_v2.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ + + enable_text_to_speech = proto.Field( + proto.BOOL, + number=1, + ) + output_audio_encoding = proto.Field( + proto.ENUM, + number=2, + enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=3, + ) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) + + +class ListEnvironmentsRequest(proto.Message): + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + environment_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self + + parent = proto.Field( + proto.STRING, + number=1, + ) + entries = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Entry, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py new file mode 100644 index 000000000..85b91ad3b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + }, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + Optional. The human-readable name of the + fulfillment, unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + enabled (bool): + Optional. Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.Feature]): + Optional. The field defines whether the + fulfillment is enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + Optional. The user name for HTTP Basic + authentication. + password (str): + Optional. The password for HTTP Basic + authentication. + request_headers (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + Optional. The HTTP request headers to send + together with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + username = proto.Field( + proto.STRING, + number=2, + ) + password = proto.Field( + proto.STRING, + number=3, + ) + request_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + is_cloud_function = proto.Field( + proto.BOOL, + number=5, + ) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + Attributes: + type_ (google.cloud.dialogflow_v2.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Fulfillment.Feature.Type', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=3, + oneof='fulfillment', + message=GenericWebService, + ) + enabled = proto.Field( + proto.BOOL, + number=4, + ) + features = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Feature, + ) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field( + proto.MESSAGE, + number=1, + message='Fulfillment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py new file mode 100644 index 000000000..16651cf55 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + }, +) + + +__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 new file mode 100644 index 000000000..625acf227 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): + The suggestion results payload that this + notification refers to. + """ + + conversation = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.STRING, + number=3, + ) + suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_participant.SuggestionResult, + ) + + +__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 new file mode 100644 index 000000000..4ef1e4beb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py @@ -0,0 +1,1611 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + """ + 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 (Sequence[str]): + Optional. The list of context names required for this intent + to be triggered. Format: + ``projects//agent/sessions/-/contexts/``. + events (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.Intent.Parameter]): + Optional. The collection of parameters + associated with the intent. + messages (Sequence[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 (Sequence[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): + 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 (Sequence[google.cloud.dialogflow_v2.types.Intent.FollowupIntentInfo]): + 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.""" + 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 (Sequence[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.""" + 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + alias = proto.Field( + proto.STRING, + number=3, + ) + user_defined = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='Intent.TrainingPhrase.Type', + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Intent.TrainingPhrase.Part', + ) + times_added_count = proto.Field( + proto.INT32, + number=4, + ) + + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + default_value = proto.Field( + proto.STRING, + number=4, + ) + entity_type_display_name = proto.Field( + proto.STRING, + number=5, + ) + mandatory = proto.Field( + proto.BOOL, + number=6, + ) + prompts = proto.RepeatedField( + proto.STRING, + number=7, + ) + is_list = proto.Field( + proto.BOOL, + number=8, + ) + + class Message(proto.Message): + r"""A rich response message. Corresponds to the intent ``Response`` + field in the Dialogflow console. For more information, see `Rich + response + messages `__. + + Attributes: + text (google.cloud.dialogflow_v2.types.Intent.Message.Text): + The text response. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + The image response. + quick_replies (google.cloud.dialogflow_v2.types.Intent.Message.QuickReplies): + The quick replies response. + card (google.cloud.dialogflow_v2.types.Intent.Message.Card): + The card response. + payload (google.protobuf.struct_pb2.Struct): + A custom platform-specific response. + simple_responses (google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponses): + The voice and text-only responses for Actions + on Google. + basic_card (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard): + The basic card response for Actions on + Google. + suggestions (google.cloud.dialogflow_v2.types.Intent.Message.Suggestions): + The suggestion chips for Actions on Google. + link_out_suggestion (google.cloud.dialogflow_v2.types.Intent.Message.LinkOutSuggestion): + The link out suggestion chip for Actions on + Google. + list_select (google.cloud.dialogflow_v2.types.Intent.Message.ListSelect): + The list card response for Actions on Google. + carousel_select (google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect): + The carousel card response for Actions on + Google. + browse_carousel_card (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard): + Browse carousel card for Actions on Google. + table_card (google.cloud.dialogflow_v2.types.Intent.Message.TableCard): + Table card for Actions on Google. + media_content (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent): + The media content card for Actions on Google. + 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 `__. + """ + 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 (Sequence[str]): + Optional. The collection of the agent's + responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Image(proto.Message): + r"""The image response message. + Attributes: + image_uri (str): + Optional. The public URI to an image file. + accessibility_text (str): + Optional. A text description of the image to + be used for accessibility, e.g., screen readers. + """ + + image_uri = proto.Field( + proto.STRING, + number=1, + ) + accessibility_text = proto.Field( + proto.STRING, + number=2, + ) + + class QuickReplies(proto.Message): + r"""The quick replies response message. + Attributes: + title (str): + Optional. The title of the collection of + quick replies. + quick_replies (Sequence[str]): + Optional. The collection of quick replies. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + quick_replies = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Card(proto.Message): + r"""The card response message. + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + image_uri (str): + Optional. The public URI to an image file for + the card. + buttons (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + postback = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image_uri = proto.Field( + proto.STRING, + number=3, + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.Card.Button', + ) + + class SimpleResponse(proto.Message): + r"""The simple response message containing speech or text. + Attributes: + text_to_speech (str): + One of text_to_speech or ssml must be provided. The plain + 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 = proto.Field( + proto.STRING, + number=1, + ) + ssml = proto.Field( + proto.STRING, + number=2, + ) + display_text = proto.Field( + proto.STRING, + number=3, + ) + + class SimpleResponses(proto.Message): + r"""The collection of simple response candidates. This message in + ``QueryResult.fulfillment_messages`` and + ``WebhookResponse.fulfillment_messages`` should contain only one + ``SimpleResponse``. + + Attributes: + simple_responses (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponse]): + Required. The list of simple responses. + """ + + simple_responses = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + open_uri_action = proto.Field( + proto.MESSAGE, + number=2, + message='Intent.Message.BasicCard.Button.OpenUriAction', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + formatted_text = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + buttons = 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 = proto.Field( + proto.STRING, + number=1, + ) + + class Suggestions(proto.Message): + r"""The collection of suggestions. + Attributes: + suggestions (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): + Required. The list of suggested replies. + """ + + suggestions = 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 = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + + class ListSelect(proto.Message): + r"""The card for presenting a list of options to select from. + Attributes: + title (str): + Optional. The overall title of the list. + items (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + items = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.ListSelect.Item', + ) + subtitle = proto.Field( + proto.STRING, + number=3, + ) + + class CarouselSelect(proto.Message): + r"""The card for presenting a carousel of options to select from. + Attributes: + items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): + Required. Carousel items. + """ + + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + items = 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 (Sequence[str]): + Optional. A list of synonyms that can also be + used to trigger this item in dialog. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class MediaContent(proto.Message): + r"""The media content card for Actions on Google. + Attributes: + media_type (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaType): + Optional. What type of media is the content + (ie "audio"). + media_objects (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaObject]): + Required. List of media objects. + """ + class ResponseMediaType(proto.Enum): + r"""Format of response media type.""" + RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + + class ResponseMediaObject(proto.Message): + r"""Response media object for media content card. + 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. + icon (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. Icon to display above media + content. + content_url (str): + Required. Url where the media is stored. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + large_image = proto.Field( + proto.MESSAGE, + number=3, + oneof='image', + message='Intent.Message.Image', + ) + icon = proto.Field( + proto.MESSAGE, + number=4, + oneof='image', + message='Intent.Message.Image', + ) + content_url = proto.Field( + proto.STRING, + number=5, + ) + + media_type = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.MediaContent.ResponseMediaType', + ) + media_objects = 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 (Sequence[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. + """ + 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.""" + URL_TYPE_HINT_UNSPECIFIED = 0 + AMP_ACTION = 1 + AMP_CONTENT = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + url_type_hint = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', + ) + + open_uri_action = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + footer = proto.Field( + proto.STRING, + number=5, + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', + ) + image_display_options = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties]): + Optional. Display properties for the columns + in this table. + rows (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardRow]): + Optional. Rows in this table of data. + buttons (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): + Optional. List of buttons for the card. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.Image', + ) + column_properties = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.ColumnProperties', + ) + rows = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.TableCardRow', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Intent.Message.BasicCard.Button', + ) + + 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.""" + HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 + LEADING = 1 + CENTER = 2 + TRAILING = 3 + + header = proto.Field( + proto.STRING, + number=1, + ) + horizontal_alignment = 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 (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.TableCardCell', + ) + divider_after = 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 = proto.Field( + proto.STRING, + number=1, + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='Intent.Message.Text', + ) + image = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Intent.Message.Image', + ) + quick_replies = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message='Intent.Message.QuickReplies', + ) + card = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message='Intent.Message.Card', + ) + payload = proto.Field( + proto.MESSAGE, + number=5, + oneof='message', + message=struct_pb2.Struct, + ) + simple_responses = proto.Field( + proto.MESSAGE, + number=7, + oneof='message', + message='Intent.Message.SimpleResponses', + ) + basic_card = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message='Intent.Message.BasicCard', + ) + suggestions = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message='Intent.Message.Suggestions', + ) + link_out_suggestion = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message='Intent.Message.LinkOutSuggestion', + ) + list_select = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message='Intent.Message.ListSelect', + ) + carousel_select = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message='Intent.Message.CarouselSelect', + ) + browse_carousel_card = proto.Field( + proto.MESSAGE, + number=22, + oneof='message', + message='Intent.Message.BrowseCarouselCard', + ) + table_card = proto.Field( + proto.MESSAGE, + number=23, + oneof='message', + message='Intent.Message.TableCard', + ) + media_content = proto.Field( + proto.MESSAGE, + number=24, + oneof='message', + message='Intent.Message.MediaContent', + ) + platform = proto.Field( + proto.ENUM, + number=6, + enum='Intent.Message.Platform', + ) + + class FollowupIntentInfo(proto.Message): + r"""Represents a single followup intent in the chain. + Attributes: + followup_intent_name (str): + The unique identifier of the followup intent. Format: + ``projects//agent/intents/``. + parent_followup_intent_name (str): + The unique identifier of the followup intent's parent. + Format: ``projects//agent/intents/``. + """ + + followup_intent_name = proto.Field( + proto.STRING, + number=1, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + webhook_state = proto.Field( + proto.ENUM, + number=6, + enum=WebhookState, + ) + priority = proto.Field( + proto.INT32, + number=3, + ) + is_fallback = proto.Field( + proto.BOOL, + number=4, + ) + ml_disabled = proto.Field( + proto.BOOL, + number=19, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=20, + ) + end_interaction = proto.Field( + proto.BOOL, + number=21, + ) + input_context_names = proto.RepeatedField( + proto.STRING, + number=7, + ) + events = proto.RepeatedField( + proto.STRING, + number=8, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=TrainingPhrase, + ) + action = proto.Field( + proto.STRING, + number=10, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=12, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Parameter, + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=Message, + ) + default_response_platforms = proto.RepeatedField( + proto.ENUM, + number=15, + enum=Message.Platform, + ) + root_followup_intent_name = proto.Field( + proto.STRING, + number=16, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=17, + ) + followup_intent_info = 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``. + 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + + Attributes: + intents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = 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 = proto.Field( + proto.STRING, + number=1, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + intent_view = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + intent_view = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateIntentsRequest(proto.Message): + r""" + Attributes: + parent (str): + Required. The name of the agent to update or create intents + 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://". + intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): + The collection of intents 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. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='intent_batch', + ) + intent_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='intent_batch', + message='IntentBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + intent_view = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent]): + The collection of updated or created intents. + """ + + intents = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent]): + Required. The collection of intents to delete. Only intent + ``name`` must be filled in. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent', + ) + + +class IntentBatch(proto.Message): + r"""This message is a wrapper around a collection of intents. + Attributes: + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + A collection of intents. + """ + + intents = 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 new file mode 100644 index 000000000..e66b99a29 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + '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 = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKnowledgeBasesRequest(proto.Message): + 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListKnowledgeBasesResponse(proto.Message): + r"""Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + knowledge_bases (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + knowledge_base = 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 = proto.Field( + proto.STRING, + number=1, + ) + force = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + update_mask = 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 new file mode 100644 index 000000000..85e2f148a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py @@ -0,0 +1,836 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import 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', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'OutputAudio', + 'AutomatedAgentReply', + 'ArticleAnswer', + 'FaqAnswer', + 'SuggestionResult', + 'AnnotatedMessagePart', + 'MessageAnnotation', + }, +) + + +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. + """ + class Role(proto.Enum): + r"""Enumeration of the roles a participant can play in a + conversation. + """ + ROLE_UNSPECIFIED = 0 + HUMAN_AGENT = 1 + AUTOMATED_AGENT = 2 + END_USER = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + role = proto.Field( + proto.ENUM, + number=2, + enum=Role, + ) + sip_recording_media_label = proto.Field( + proto.STRING, + number=6, + ) + + +class Message(proto.Message): + r"""Represents a message posted into a conversation. + Attributes: + name (str): + 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. + message_annotation (google.cloud.dialogflow_v2.types.MessageAnnotation): + Output only. The annotation for the message. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + content = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + participant = proto.Field( + proto.STRING, + number=4, + ) + participant_role = proto.Field( + proto.ENUM, + number=5, + enum='Participant.Role', + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + message_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='MessageAnnotation', + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListParticipantsResponse(proto.Message): + r"""The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + + Attributes: + participants (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Participant', + ) + next_page_token = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Participant', + ) + update_mask = 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]. + + 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. + event_input (google.cloud.dialogflow_v2.types.EventInput): + An input event to send to Dialogflow. + 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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + text_input = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message=session.TextInput, + ) + event_input = proto.Field( + proto.MESSAGE, + number=8, + oneof='input', + message=session.EventInput, + ) + reply_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + query_params = proto.Field( + proto.MESSAGE, + number=9, + message=session.QueryParameters, + ) + request_id = proto.Field( + proto.STRING, + number=11, + ) + + +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 = 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 (Sequence[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 (Sequence[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. + """ + + reply_text = proto.Field( + proto.STRING, + number=1, + ) + reply_audio = proto.Field( + proto.MESSAGE, + number=2, + message='OutputAudio', + ) + automated_agent_reply = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentReply', + ) + message = proto.Field( + proto.MESSAGE, + number=5, + message='Message', + ) + human_agent_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='SuggestionResult', + ) + end_user_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='SuggestionResult', + ) + dtmf_parameters = proto.Field( + proto.MESSAGE, + number=9, + message='DtmfParameters', + ) + + +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): + 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][google.cloud.dialogflow.v2.SuggestArticlesRequest.latest_message] + to use as context when compiling the suggestion. By default + 20 and at most 50. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestArticlesResponse(proto.Message): + r"""The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + + Attributes: + article_answers (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ArticleAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = 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): + 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 = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestFaqAnswersResponse(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + + Attributes: + faq_answers (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FaqAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = 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 = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.OutputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class AutomatedAgentReply(proto.Message): + r"""Represents a response from an automated agent. + Attributes: + detect_intent_response (google.cloud.dialogflow_v2.types.DetectIntentResponse): + Response of the Dialogflow + [Sessions.DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] + call. + """ + + detect_intent_response = proto.Field( + proto.MESSAGE, + number=1, + message=session.DetectIntentResponse, + ) + + +class ArticleAnswer(proto.Message): + r"""Represents article answer. + Attributes: + title (str): + The article title. + uri (str): + The article URI. + snippets (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.ArticleAnswer.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class FaqAnswer(proto.Message): + r"""Represents answer from "frequently asked questions". + Attributes: + answer (str): + The piece of text from the ``source`` knowledge base + 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 (Sequence[google.cloud.dialogflow_v2.types.FaqAnswer.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class SuggestionResult(proto.Message): + 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]. + + Attributes: + error (google.rpc.status_pb2.Status): + Error status if the request failed. + suggest_articles_response (google.cloud.dialogflow_v2.types.SuggestArticlesResponse): + SuggestArticlesResponse if request is for + ARTICLE_SUGGESTION. + suggest_faq_answers_response (google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse): + SuggestFaqAnswersResponse if request is for FAQ_ANSWER. + """ + + error = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion_response', + message=status_pb2.Status, + ) + suggest_articles_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='suggestion_response', + message='SuggestArticlesResponse', + ) + suggest_faq_answers_response = proto.Field( + proto.MESSAGE, + number=3, + oneof='suggestion_response', + message='SuggestFaqAnswersResponse', + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + formatted_value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + +class MessageAnnotation(proto.Message): + r"""Represents the result of annotation for the message. + Attributes: + parts (Sequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): + The collection of annotated message parts ordered by their + 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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnnotatedMessagePart', + ) + contain_entities = proto.Field( + proto.BOOL, + number=2, + ) + + +__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 new file mode 100644 index 000000000..37e736830 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py @@ -0,0 +1,964 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=5, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + Attributes: + response_id (str): + The unique identifier of the response. It can + 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 = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = 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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.QueryParameters.WebhookHeadersEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + geo_location = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + contexts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=4, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + sentiment_analysis_request_config = proto.Field( + proto.MESSAGE, + number=10, + message='SentimentAnalysisRequestConfig', + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +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. + + Attributes: + audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): + Instructs the speech recognizer how to + process the speech audio. + text (google.cloud.dialogflow_v2.types.TextInput): + The natural language text to be processed. + event (google.cloud.dialogflow_v2.types.EventInput): + The event to be processed. + """ + + audio_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='input', + message=gcd_audio_config.InputAudioConfig, + ) + text = proto.Field( + proto.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + event = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='EventInput', + ) + + +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. + 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 (Sequence[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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + speech_recognition_confidence = proto.Field( + proto.FLOAT, + number=2, + ) + action = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + all_required_params_present = proto.Field( + proto.BOOL, + number=5, + ) + fulfillment_text = proto.Field( + proto.STRING, + number=6, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, + ) + webhook_source = proto.Field( + proto.STRING, + number=8, + ) + webhook_payload = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=context.Context, + ) + intent = proto.Field( + proto.MESSAGE, + number=11, + message=gcd_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=12, + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=14, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = 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 = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + single_utterance = proto.Field( + proto.BOOL, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = 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 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. 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 = proto.Field( + proto.STRING, + number=1, + ) + recognition_result = proto.Field( + proto.MESSAGE, + number=2, + message='StreamingRecognitionResult', + ) + query_result = proto.Field( + proto.MESSAGE, + number=3, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=5, + ) + output_audio_config = 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. + + Example: + + 1. transcript: "tube" + + 2. transcript: "to be a" + + 3. transcript: "to be" + + 4. transcript: "to be or not to be" is_final: true + + 5. transcript: " that's" + + 6. transcript: " that is" + + 7. message_type: ``END_OF_SINGLE_UTTERANCE`` + + 8. transcript: " that is the question" is_final: true + + Only two of the responses contain final results (#4 and #8 indicated + by ``is_final: true``). Concatenating these generates the full + transcript: "to be or not to be that is the question". + + In each response we populate: + + - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. + + - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. + + 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 (Sequence[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``. + """ + class MessageType(proto.Enum): + r"""Type of the response message.""" + MESSAGE_TYPE_UNSPECIFIED = 0 + TRANSCRIPT = 1 + END_OF_SINGLE_UTTERANCE = 2 + + message_type = proto.Field( + proto.ENUM, + number=1, + enum=MessageType, + ) + transcript = proto.Field( + proto.STRING, + number=2, + ) + is_final = proto.Field( + proto.BOOL, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class TextInput(proto.Message): + r"""Represents the natural language text to be processed. + Attributes: + text (str): + Required. The UTF-8 encoded natural language + text to be processed. Text length must not + exceed 256 characters. + 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class SentimentAnalysisRequestConfig(proto.Message): + r"""Configures the types of sentiment analysis to perform. + Attributes: + analyze_query_text_sentiment (bool): + Instructs the service to perform sentiment analysis on + ``query_text``. If not provided, sentiment analysis is not + performed on ``query_text``. + """ + + analyze_query_text_sentiment = 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 = 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. + + 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 = proto.Field( + proto.FLOAT, + number=1, + ) + magnitude = 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 new file mode 100644 index 000000000..6924dfd26 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 (Sequence[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.""" + ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 + ENTITY_OVERRIDE_MODE_OVERRIDE = 1 + ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + entity_override_mode = proto.Field( + proto.ENUM, + number=2, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=entity_type.EntityType.Entity, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + session_entity_type = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + update_mask = 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 = 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 new file mode 100644 index 000000000..ff4f05e76 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__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 (Sequence[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 messsage. + """ + class Severity(proto.Enum): + r"""Represents a level of severity.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + CRITICAL = 4 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + entries = proto.RepeatedField( + proto.STRING, + number=3, + ) + error_message = proto.Field( + proto.STRING, + number=4, + ) + + +class ValidationResult(proto.Message): + r"""Represents the output of agent validation. + Attributes: + validation_errors (Sequence[google.cloud.dialogflow_v2.types.ValidationError]): + Contains all validation errors. + """ + + validation_errors = 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 new file mode 100644 index 000000000..aad1a9afa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + version_number = proto.Field( + proto.INT32, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.ENUM, + number=6, + enum=VersionStatus, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Version', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field( + proto.MESSAGE, + number=1, + message='Version', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py new file mode 100644 index 000000000..cbbb1af87 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 = proto.Field( + proto.STRING, + number=4, + ) + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.QueryResult, + ) + original_detect_intent_request = proto.Field( + proto.MESSAGE, + number=3, + message='OriginalDetectIntentRequest', + ) + + +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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=intent.Intent.Message, + ) + source = proto.Field( + proto.STRING, + number=3, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=context.Context, + ) + followup_event_input = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_session.EventInput, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=session_entity_type.SessionEntityType, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + payload = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 000000000..3b2c9dcdd --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/dialogflow_v2/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) diff --git a/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py new file mode 100644 index 000000000..cc0f68eb9 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py @@ -0,0 +1,257 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'content_uri', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + 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: not a.keyword.value 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 new file mode 100644 index 000000000..4601e7528 --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-dialogflow', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/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 new file mode 100644 index 000000000..00c530ea3 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py @@ -0,0 +1,3145 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.agents import AgentsAsyncClient +from google.cloud.dialogflow_v2.services.agents import AgentsClient +from google.cloud.dialogflow_v2.services.agents import pagers +from google.cloud.dialogflow_v2.services.agents import transports +from google.cloud.dialogflow_v2.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.agents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_client_get_transport_class(): + transport = AgentsClient.get_transport_class() + available_transports = [ + transports.AgentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): + 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.2552, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +def test_get_agent_from_dict(): + test_get_agent(request_type=dict) + + +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.2552, + 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.2552, 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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): + 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.2552, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + ) + response = client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +def test_set_agent_from_dict(): + test_set_agent(request_type=dict) + + +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.2552, + 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.2552, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +@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 = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = gcd_agent.Agent() + client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=agent.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 = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + 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=agent.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] + assert args[0].agent == gcd_agent.Agent(parent='parent_value') + + +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] + assert args[0].agent == gcd_agent.Agent(parent='parent_value') + + +@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'), + ) + + +def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): + 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_from_dict(): + test_delete_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): + 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_from_dict(): + test_search_agents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) + for i in results) + +def test_search_agents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): + 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_from_dict(): + test_train_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): + 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_from_dict(): + test_export_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): + 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_from_dict(): + test_import_agent(request_type=dict) + + +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'] + + +def test_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): + 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_from_dict(): + test_restore_agent(request_type=dict) + + +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'] + + +def test_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): + 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_from_dict(): + test_get_validation_result(request_type=dict) + + +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'] + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_agents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_agents_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_agents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_agents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_agents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_agents_host_no_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_host_with_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..ef6a2489b --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py @@ -0,0 +1,1661 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsAsyncClient +from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsClient +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.services.answer_records import transports +from google.cloud.dialogflow_v2.services.answer_records.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.answer_records.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.cloud.dialogflow_v2.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_client_get_transport_class(): + transport = AnswerRecordsClient.get_transport_class() + available_transports = [ + transports.AnswerRecordsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): + 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_from_dict(): + test_list_answer_records(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, answer_record.AnswerRecord) + for i in results) + +def test_list_answer_records_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_update_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + 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_from_dict(): + test_update_answer_record(request_type=dict) + + +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 = 'answer_record.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=answer_record.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 = 'answer_record.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=answer_record.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] + assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=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']), + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_answer_records_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_answer_records_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_answer_records_host_no_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_host_with_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..121896027 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py @@ -0,0 +1,2595 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.contexts import ContextsAsyncClient +from google.cloud.dialogflow_v2.services.contexts import ContextsClient +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.services.contexts import transports +from google.cloud.dialogflow_v2.services.contexts.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.contexts.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_client_get_transport_class(): + transport = ContextsClient.get_transport_class() + available_transports = [ + transports.ContextsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): + 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_from_dict(): + test_list_contexts(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, context.Context) + for i in results) + +def test_list_contexts_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): + 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_from_dict(): + test_get_context(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): + 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_from_dict(): + test_create_context(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].context == gcd_context.Context(name='name_value') + + +def test_create_context_flattened_error(): + client = ContextsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].context == gcd_context.Context(name='name_value') + + +@pytest.mark.asyncio +async def test_create_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=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'), + ) + + +def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): + 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_from_dict(): + test_update_context(request_type=dict) + + +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 = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=context.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 = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + 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=context.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] + assert args[0].context == gcd_context.Context(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].context == gcd_context.Context(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=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']), + ) + + +def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): + 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_from_dict(): + test_delete_context(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): + 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_from_dict(): + test_delete_all_contexts(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_contexts_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_contexts_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_contexts_host_no_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_host_with_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..64ef56a29 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py @@ -0,0 +1,2458 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.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.services.conversation_profiles.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_client_get_transport_class(): + transport = ConversationProfilesClient.get_transport_class() + available_transports = [ + transports.ConversationProfilesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): + 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_from_dict(): + test_list_conversation_profiles(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation_profile.ConversationProfile) + for i in results) + +def test_list_conversation_profiles_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): + 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', + ) + 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' + + +def test_get_conversation_profile_from_dict(): + test_get_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + 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', + ) + 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' + + +def test_create_conversation_profile_from_dict(): + test_create_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].parent == 'parent_value' + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + + +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] + assert args[0].parent == 'parent_value' + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + + +@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'), + ) + + +def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + 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', + ) + 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' + + +def test_update_conversation_profile_from_dict(): + test_update_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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 = 'conversation_profile.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=conversation_profile.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 = 'conversation_profile.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=conversation_profile.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] + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=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']), + ) + + +def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): + 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_from_dict(): + test_delete_conversation_profile(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_conversation_profiles_host_no_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_host_with_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_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 = ConversationProfilesClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", + } + 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 = "cuttlefish" + knowledge_base = "mussel" + 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": "winkle", + "knowledge_base": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationProfilesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationProfilesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = ConversationProfilesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..3ddeb0393 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py @@ -0,0 +1,2618 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.conversations import ConversationsAsyncClient +from google.cloud.dialogflow_v2.services.conversations import ConversationsClient +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.services.conversations import transports +from google.cloud.dialogflow_v2.services.conversations.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.conversations.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_client_get_transport_class(): + transport = ConversationsClient.get_transport_class() + available_transports = [ + transports.ConversationsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): + 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_from_dict(): + test_create_conversation(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].conversation == gcd_conversation.Conversation(name='name_value') + + +def test_create_conversation_flattened_error(): + client = ConversationsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].conversation == gcd_conversation.Conversation(name='name_value') + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=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'), + ) + + +def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): + 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_from_dict(): + test_list_conversations(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + +def test_list_conversations_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): + 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_from_dict(): + test_get_conversation(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): + 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_from_dict(): + test_complete_conversation(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): + 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_from_dict(): + test_list_messages(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Message) + for i in results) + +def test_list_messages_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_conversations_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_conversations_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_conversations_host_no_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_host_with_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_conversation_path(): + project = "squid" + conversation = "clam" + 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": "whelk", + "conversation": "octopus", + } + 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 = "oyster" + conversation_profile = "nudibranch" + 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": "cuttlefish", + "conversation_profile": "mussel", + } + 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 = "winkle" + conversation = "nautilus" + message = "scallop" + 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": "abalone", + "conversation": "squid", + "message": "clam", + } + 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 = "whelk" + 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": "octopus", + } + 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 = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + 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 = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + 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 = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConversationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + 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 = "scallop" + location = "abalone" + 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": "squid", + "location": "clam", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..e8c229933 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py @@ -0,0 +1,2655 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.documents import DocumentsAsyncClient +from google.cloud.dialogflow_v2.services.documents import DocumentsClient +from google.cloud.dialogflow_v2.services.documents import pagers +from google.cloud.dialogflow_v2.services.documents import transports +from google.cloud.dialogflow_v2.services.documents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.documents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_client_get_transport_class(): + transport = DocumentsClient.get_transport_class() + available_transports = [ + transports.DocumentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): + 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_from_dict(): + test_list_documents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + +def test_list_documents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): + 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, + 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 + + +def test_get_document_from_dict(): + test_get_document(request_type=dict) + + +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, + )) + 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 + + +@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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): + 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_from_dict(): + test_create_document(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].document == gcd_document.Document(name='name_value') + + +def test_create_document_flattened_error(): + client = DocumentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].document == gcd_document.Document(name='name_value') + + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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'), + ) + + +def test_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): + 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_from_dict(): + test_delete_document(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): + 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_from_dict(): + test_update_document(request_type=dict) + + +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 = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=document.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 = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = 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=document.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] + assert args[0].document == gcd_document.Document(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].document == gcd_document.Document(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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']), + ) + + +def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): + 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_from_dict(): + test_reload_document(request_type=dict) + + +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] + assert args[0].name == 'name_value' + 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] + assert args[0].name == 'name_value' + assert args[0].content_uri == 'content_uri_value' + + +@pytest.mark.asyncio +async def test_reload_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + 'delete_document', + 'update_document', + 'reload_document', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_documents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_documents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_documents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_documents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_documents_host_no_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_host_with_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..5dec00c3b --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py @@ -0,0 +1,3574 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflow_v2.services.entity_types import EntityTypesClient +from google.cloud.dialogflow_v2.services.entity_types import pagers +from google.cloud.dialogflow_v2.services.entity_types import transports +from google.cloud.dialogflow_v2.services.entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_client_get_transport_class(): + transport = EntityTypesClient.get_transport_class() + available_transports = [ + transports.EntityTypesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): + 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_from_dict(): + test_list_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, entity_type.EntityType) + for i in results) + +def test_list_entity_types_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): + 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_from_dict(): + test_get_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): + 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_from_dict(): + test_create_entity_type(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +def test_create_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): + 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_from_dict(): + test_update_entity_type(request_type=dict) + + +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 = 'entity_type.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=entity_type.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 = 'entity_type.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=entity_type.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] + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +def test_update_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): + 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_from_dict(): + test_delete_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): + 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_from_dict(): + test_batch_update_entity_types(request_type=dict) + + +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'] + + +def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): + 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_from_dict(): + test_batch_delete_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type_names == ['entity_type_names_value'] + + +def test_batch_delete_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type_names == ['entity_type_names_value'] + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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'], + ) + + +def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): + 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_from_dict(): + test_batch_create_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +def test_batch_create_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): + 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_from_dict(): + test_batch_update_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +def test_batch_update_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): + 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_from_dict(): + test_batch_delete_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_values == ['entity_values_value'] + assert args[0].language_code == 'language_code_value' + + +def test_batch_delete_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_values == ['entity_values_value'] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_entity_types_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_entity_types_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_entity_types_host_no_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_host_with_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..b4f486182 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py @@ -0,0 +1,2420 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.environments import EnvironmentsAsyncClient +from google.cloud.dialogflow_v2.services.environments import EnvironmentsClient +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.services.environments import transports +from google.cloud.dialogflow_v2.services.environments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.environments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): + 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_from_dict(): + test_list_environments(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(): + client = EnvironmentsClient( + credentials=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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.Environment) + for i in results) + +def test_list_environments_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): + 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_from_dict(): + test_get_environment(request_type=dict) + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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'] + + +def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + )) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_get_environment_history_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in results) + +def test_get_environment_history_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_environments', + 'get_environment', + 'create_environment', + 'update_environment', + 'delete_environment', + 'get_environment_history', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_environments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_environments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_environments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_environments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + 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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..7dc3e46b3 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py @@ -0,0 +1,1487 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments import transports +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +def test_fulfillments_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FulfillmentsGrpcTransport, + ) + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_fulfillment', + 'update_fulfillment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_fulfillments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_fulfillments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_fulfillments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/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 new file mode 100644 index 000000000..972981777 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py @@ -0,0 +1,3088 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.intents import IntentsAsyncClient +from google.cloud.dialogflow_v2.services.intents import IntentsClient +from google.cloud.dialogflow_v2.services.intents import pagers +from google.cloud.dialogflow_v2.services.intents import transports +from google.cloud.dialogflow_v2.services.intents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.intents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_client_get_transport_class(): + transport = IntentsClient.get_transport_class() + available_transports = [ + transports.IntentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): + 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_from_dict(): + test_list_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_list_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, intent.Intent) + for i in results) + +def test_list_intents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): + 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_from_dict(): + test_get_intent(request_type=dict) + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): + 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_from_dict(): + test_create_intent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + + +def test_create_intent_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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', + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): + 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_from_dict(): + test_update_intent(request_type=dict) + + +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 = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=intent.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 = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + 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=intent.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] + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@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']), + ) + + +def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): + 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_from_dict(): + test_delete_intent(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): + 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_from_dict(): + test_batch_update_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +def test_batch_update_intents_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + 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')]), + ) + + +def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): + 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_from_dict(): + test_batch_delete_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intents == [intent.Intent(name='name_value')] + + +def test_batch_delete_intents_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].intents == [intent.Intent(name='name_value')] + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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')], + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_intents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_intents_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_intents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_intents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_intents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_intents_host_no_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_host_with_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..ebaf0718f --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py @@ -0,0 +1,2378 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.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.services.knowledge_bases.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_client_get_transport_class(): + transport = KnowledgeBasesClient.get_transport_class() + available_transports = [ + transports.KnowledgeBasesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): + 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_from_dict(): + test_list_knowledge_bases(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, knowledge_base.KnowledgeBase) + for i in results) + +def test_list_knowledge_bases_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): + 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_from_dict(): + test_get_knowledge_base(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + 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_from_dict(): + test_create_knowledge_base(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + + +def test_create_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + + +@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'), + ) + + +def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + 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_from_dict(): + test_delete_knowledge_base(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + 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_from_dict(): + test_update_knowledge_base(request_type=dict) + + +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 = 'knowledge_base.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=knowledge_base.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 = 'knowledge_base.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=knowledge_base.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] + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=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']), + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_knowledge_bases_host_no_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_host_with_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..27391136a --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py @@ -0,0 +1,2957 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.participants import ParticipantsAsyncClient +from google.cloud.dialogflow_v2.services.participants import ParticipantsClient +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.services.participants import transports +from google.cloud.dialogflow_v2.services.participants.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.participants.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import entity_type +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.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 + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_client_get_transport_class(): + transport = ParticipantsClient.get_transport_class() + available_transports = [ + transports.ParticipantsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): + 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', + ) + 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' + + +def test_create_participant_from_dict(): + test_create_participant(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].parent == 'parent_value' + assert args[0].participant == gcd_participant.Participant(name='name_value') + + +def test_create_participant_flattened_error(): + client = ParticipantsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].participant == gcd_participant.Participant(name='name_value') + + +@pytest.mark.asyncio +async def test_create_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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'), + ) + + +def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): + 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', + ) + 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' + + +def test_get_participant_from_dict(): + test_get_participant(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): + 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_from_dict(): + test_list_participants(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Participant) + for i in results) + +def test_list_participants_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_update_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): + 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', + ) + 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' + + +def test_update_participant_from_dict(): + test_update_participant(request_type=dict) + + +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', + )) + 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' + + +@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 = 'participant.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=participant.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 = 'participant.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=participant.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] + assert args[0].participant == gcd_participant.Participant(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].participant == gcd_participant.Participant(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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']), + ) + + +def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): + 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_from_dict(): + test_analyze_content(request_type=dict) + + +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] + assert args[0].participant == 'participant_value' + assert args[0].event_input == session.EventInput(name='name_value') + + +def test_analyze_content_flattened_error(): + client = ParticipantsClient( + credentials=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] + assert args[0].participant == 'participant_value' + assert args[0].event_input == session.EventInput(name='name_value') + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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'), + ) + + +def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): + 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_from_dict(): + test_suggest_articles(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): + 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_from_dict(): + test_suggest_faq_answers(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + 'suggest_articles', + 'suggest_faq_answers', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_participants_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_participants_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_participants_host_no_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_host_with_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_context_path(): + project = "squid" + session = "clam" + context = "whelk" + 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": "octopus", + "session": "oyster", + "context": "nudibranch", + } + 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 = "cuttlefish" + intent = "mussel" + 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": "winkle", + "intent": "nautilus", + } + 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 = "scallop" + conversation = "abalone" + message = "squid" + 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": "clam", + "conversation": "whelk", + "message": "octopus", + } + 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 = "oyster" + conversation = "nudibranch" + participant = "cuttlefish" + 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": "mussel", + "conversation": "winkle", + "participant": "nautilus", + } + 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 = "scallop" + session = "abalone" + entity_type = "squid" + 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": "clam", + "session": "whelk", + "entity_type": "octopus", + } + 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 = "oyster" + 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": "nudibranch", + } + 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 = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ParticipantsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + 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 = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ParticipantsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + 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 = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ParticipantsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + 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 = "squid" + location = "clam" + 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": "whelk", + "location": "octopus", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..9aadedc4f --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py @@ -0,0 +1,2369 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.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.services.session_entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_client_get_transport_class(): + transport = SessionEntityTypesClient.get_transport_class() + available_transports = [ + transports.SessionEntityTypesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): + 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_from_dict(): + test_list_session_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, session_entity_type.SessionEntityType) + for i in results) + +def test_list_session_entity_types_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): + 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_from_dict(): + test_get_session_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + 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_from_dict(): + test_create_session_entity_type(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + + +def test_create_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + + +@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'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + 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_from_dict(): + test_update_session_entity_type(request_type=dict) + + +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 = 'session_entity_type.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=session_entity_type.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 = 'session_entity_type.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=session_entity_type.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] + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=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']), + ) + + +def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + 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_from_dict(): + test_delete_session_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_session_entity_types_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_session_entity_types_host_no_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_host_with_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..eaea25782 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py @@ -0,0 +1,1381 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.sessions import SessionsAsyncClient +from google.cloud.dialogflow_v2.services.sessions import SessionsClient +from google.cloud.dialogflow_v2.services.sessions import transports +from google.cloud.dialogflow_v2.services.sessions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.sessions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import entity_type +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.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 + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_client_get_transport_class(): + transport = SessionsClient.get_transport_class() + available_transports = [ + transports.SessionsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): + 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_from_dict(): + test_detect_intent(request_type=dict) + + +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] + assert args[0].session == 'session_value' + assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + + +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] + assert args[0].session == 'session_value' + assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + + +@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)), + ) + + +def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): + 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) + + +def test_streaming_detect_intent_from_dict(): + test_streaming_detect_intent(request_type=dict) + + +@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) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_sessions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_sessions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_sessions_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_sessions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_sessions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_sessions_host_no_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_host_with_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..9bfb7a9a8 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py @@ -0,0 +1,2391 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2.services.versions import VersionsClient +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.services.versions import transports +from google.cloud.dialogflow_v2.services.versions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +def test_versions_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +def test_list_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = version.ListVersionsResponse() + client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_versions_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_versions_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_versions_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +def test_list_versions_pager(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) + for i in results) + +def test_list_versions_pages(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = list(client.list_versions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_versions_async_pager(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_versions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, version.Version) + for i in responses) + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +def test_get_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = version.Version() + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_version( + version.GetVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_version( + version.GetVersionRequest(), + name='name_value', + ) + + +def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +def test_create_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].version == gcd_version.Version(name='name_value') + + +def test_create_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].version == gcd_version.Version(name='name_value') + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +def test_update_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +def test_update_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +def test_delete_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = None + client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VersionsGrpcTransport, + ) + +def test_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_versions', + 'get_version', + 'create_version', + 'update_version', + 'delete_version', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_versions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_versions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_versions_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_versions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_versions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2beta1/MANIFEST.in b/owl-bot-staging/v2beta1/MANIFEST.in new file mode 100644 index 000000000..a267e6fb4 --- /dev/null +++ b/owl-bot-staging/v2beta1/MANIFEST.in @@ -0,0 +1,2 @@ +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 new file mode 100644 index 000000000..6a2fa7289 --- /dev/null +++ b/owl-bot-staging/v2beta1/README.rst @@ -0,0 +1,49 @@ +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 new file mode 100644 index 000000000..8b2599a7e --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-dialogflow" +copyright = u"2020, 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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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 new file mode 100644 index 000000000..154fdf432 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..1f890c79c --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..e6be19355 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..959fe3698 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..60267bd79 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..7151feda6 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..99defb836 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..3c4d6f333 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..33be7d8a0 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst @@ -0,0 +1,6 @@ +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 new file mode 100644 index 000000000..50e85e80d --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..70e0d5ab6 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..b2a73ebe3 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..dc7790aa3 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst @@ -0,0 +1,20 @@ +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 new file mode 100644 index 000000000..4fe3bcb31 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst @@ -0,0 +1,10 @@ +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 new file mode 100644 index 000000000..da6517c63 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst @@ -0,0 +1,6 @@ +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 new file mode 100644 index 000000000..f4c430d5a --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflow v2beta1 API +============================================= + +.. automodule:: google.cloud.dialogflow_v2beta1.types + :members: + :undoc-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 new file mode 100644 index 000000000..c74ba0edf --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/index.rst b/owl-bot-staging/v2beta1/docs/index.rst new file mode 100644 index 000000000..ffce78914 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/index.rst @@ -0,0 +1,7 @@ +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 new file mode 100644 index 000000000..ddb313040 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from 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 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_event import ConversationEvent +from google.cloud.dialogflow_v2beta1.types.conversation_profile import AutomatedAgentConfig +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 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 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 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 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 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 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', + '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', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + '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', + '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', + 'AutomatedAgentReply', + 'CompileSuggestionRequest', + 'CompileSuggestionResponse', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'ListSuggestionsRequest', + 'ListSuggestionsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'ResponseMessage', + 'SmartReplyAnswer', + '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/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed @@ -0,0 +1,2 @@ +# 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 new file mode 100644 index 000000000..f2a29bbc0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .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 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_event import ConversationEvent +from .types.conversation_profile import AutomatedAgentConfig +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 UpdateConversationProfileRequest +from .types.document import CreateDocumentRequest +from .types.document import DeleteDocumentRequest +from .types.document import Document +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 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 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 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 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', +'AudioEncoding', +'AutomatedAgentConfig', +'AutomatedAgentReply', +'BatchCreateEntitiesRequest', +'BatchCreateMessagesRequest', +'BatchCreateMessagesResponse', +'BatchDeleteEntitiesRequest', +'BatchDeleteEntityTypesRequest', +'BatchDeleteIntentsRequest', +'BatchUpdateEntitiesRequest', +'BatchUpdateEntityTypesRequest', +'BatchUpdateEntityTypesResponse', +'BatchUpdateIntentsRequest', +'BatchUpdateIntentsResponse', +'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', +'FaqAnswer', +'Fulfillment', +'FulfillmentsClient', +'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', +'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', +'SmartReplyAnswer', +'SpeechContext', +'SpeechModelVariant', +'SpeechToTextConfig', +'SpeechWordInfo', +'SsmlVoiceGender', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SubAgent', +'SuggestArticlesRequest', +'SuggestArticlesResponse', +'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 new file mode 100644 index 000000000..ed94b0a54 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json @@ -0,0 +1,1099 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2beta1", + "protoPackage": "google.cloud.dialogflow.v2beta1", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed @@ -0,0 +1,2 @@ +# 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 new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/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 new file mode 100644 index 000000000..057c8b80b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..adb33924f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AgentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: agent.GetAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_agent.SetAgentRequest = None, + *, + agent: gcd_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.SetAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: agent.DeleteAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.SearchAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.TrainAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.TrainAgentRequest`): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.ExportAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified agent to a ZIP file. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ExportAgentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: agent.ImportAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ImportAgentRequest`): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.RestoreAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest`): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.GetValidationResultRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest`): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..188371dd7 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py @@ -0,0 +1,1120 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AgentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AgentsTransport): + # transport is a AgentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_agent(self, + request: agent.GetAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_agent.SetAgentRequest = None, + *, + agent: gcd_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.SetAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: agent.DeleteAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.SearchAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.TrainAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.TrainAgentRequest): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.ExportAgentRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified agent to a ZIP file. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.ExportAgentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: agent.ImportAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ImportAgentRequest): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.RestoreAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + Args: + request (google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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: agent.GetValidationResultRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..cf43dbf95 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..0dc0c06c1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AgentsTransport +from .grpc import AgentsGrpcTransport +from .grpc_asyncio import AgentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] +_transport_registry['grpc'] = AgentsGrpcTransport +_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport + +__all__ = ( + 'AgentsTransport', + 'AgentsGrpcTransport', + 'AgentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..6c398be5f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..90a987a48 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py @@ -0,0 +1,524 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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'] + + +__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 new file mode 100644 index 000000000..3fa205d80 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation An operation + which tracks when importing is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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. + + Operation An operation + which tracks when restoring is complete. It only tracks when the + draft agent is updated not when it is done training. + + 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'] + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..16c67859b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..aa8051b2d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py @@ -0,0 +1,457 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.answer_records import pagers +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", + client_options: 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: answer_record.GetAnswerRecordRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> answer_record.AnswerRecord: + r"""Deprecated. + Retrieves a specific answer record. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest`): + The request object. Request message for + [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + 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: answer_record.ListAnswerRecordsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsAsyncPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_answer_record.UpdateAnswerRecordRequest = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..9db31e2c2 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py @@ -0,0 +1,645 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.answer_records import pagers +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnswerRecordsGrpcTransport +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AnswerRecordsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AnswerRecordsTransport): + # transport is a AnswerRecordsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_answer_record(self, + request: answer_record.GetAnswerRecordRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> answer_record.AnswerRecord: + r"""Deprecated. + Retrieves a specific answer record. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest): + The request object. Request message for + [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + # 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: answer_record.ListAnswerRecordsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_answer_record.UpdateAnswerRecordRequest = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..edb3335e1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..99c08cf37 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AnswerRecordsTransport +from .grpc import AnswerRecordsGrpcTransport +from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] +_transport_registry['grpc'] = AnswerRecordsGrpcTransport +_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport + +__all__ = ( + 'AnswerRecordsTransport', + 'AnswerRecordsGrpcTransport', + 'AnswerRecordsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..52355459d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..12746971d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_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'] + + +__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 new file mode 100644 index 000000000..cc5c09823 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .grpc import AnswerRecordsGrpcTransport + + +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_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'] + + +__all__ = ( + 'AnswerRecordsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..b0d60f297 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..50269a13b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py @@ -0,0 +1,731 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ContextsTransport] = "grpc_asyncio", + client_options: 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: context.ListContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsAsyncPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListContextsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: context.GetContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_context.CreateContextRequest = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: context.DeleteContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteContextRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: context.DeleteAllContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..768e5b840 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py @@ -0,0 +1,918 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import field_mask_pb2 # 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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ContextsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ContextsTransport): + # transport is a ContextsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_contexts(self, + request: context.ListContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListContextsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: context.GetContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_context.CreateContextRequest = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: context.DeleteContextRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteContextRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: context.DeleteAllContextsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..841a02576 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..eb854f545 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ContextsTransport +from .grpc import ContextsGrpcTransport +from .grpc_asyncio import ContextsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] +_transport_registry['grpc'] = ContextsGrpcTransport +_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport + +__all__ = ( + 'ContextsTransport', + 'ContextsGrpcTransport', + 'ContextsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..370c9e503 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..1da845890 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..99b6afc78 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'ContextsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..3e8e4ea19 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..2e086cd48 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.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.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) + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", + client_options: 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: conversation_profile.ListConversationProfilesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesAsyncPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation_profile.GetConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_conversation_profile.CreateConversationProfileRequest = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..9bb545a51 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py @@ -0,0 +1,817 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.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.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 + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationProfilesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationProfilesTransport): + # transport is a ConversationProfilesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_conversation_profiles(self, + request: conversation_profile.ListConversationProfilesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation_profile.GetConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_conversation_profile.CreateConversationProfileRequest = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (google.cloud.dialogflow_v2beta1.types.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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..eb34f0946 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..19a679f49 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationProfilesTransport +from .grpc import ConversationProfilesGrpcTransport +from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] +_transport_registry['grpc'] = ConversationProfilesGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport + +__all__ = ( + 'ConversationProfilesTransport', + 'ConversationProfilesGrpcTransport', + 'ConversationProfilesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..7b973512e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..dac1be9b8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..fdf396093 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'ConversationProfilesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..0445da9c4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..04d3afcd9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversations import pagers +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import timestamp_pb2 # 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 + + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ConversationsTransport] = "grpc_asyncio", + client_options: 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: gcd_conversation.CreateConversationRequest = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListConversationsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.GetConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.CompleteConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.BatchCreateMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.BatchCreateMessagesResponse: + r"""Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: conversation.ListMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListMessagesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..82762eb5d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py @@ -0,0 +1,908 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversations import pagers +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationsGrpcTransport +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationsTransport): + # transport is a ConversationsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_conversation(self, + request: gcd_conversation.CreateConversationRequest = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListConversationsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.GetConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.CompleteConversationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.BatchCreateMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.BatchCreateMessagesResponse: + r"""Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: conversation.ListMessagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListMessagesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..589dab410 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..9d9ee9030 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationsTransport +from .grpc import ConversationsGrpcTransport +from .grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] +_transport_registry['grpc'] = ConversationsGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport + +__all__ = ( + 'ConversationsTransport', + 'ConversationsGrpcTransport', + 'ConversationsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..3ae1558da --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..182b3cf23 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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'] + + +__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 new file mode 100644 index 000000000..b8fbf4386 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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'] + + +__all__ = ( + 'ConversationsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..cee70ad81 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..c5e6d4ec6 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py @@ -0,0 +1,845 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, DocumentsTransport] = "grpc_asyncio", + client_options: 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: document.ListDocumentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: document.GetDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_document.CreateDocumentRequest = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: document.ImportDocumentsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest`): + The request object. Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: document.DeleteDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest`): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_document.UpdateDocumentRequest = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: document.ReloadDocumentRequest = None, + *, + name: str = None, + gcs_source: gcs.GcsSource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..b36a4c671 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py @@ -0,0 +1,1033 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentsTransport): + # transport is a DocumentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_documents(self, + request: document.ListDocumentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: document.GetDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_document.CreateDocumentRequest = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: document.ImportDocumentsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest): + The request object. Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: document.DeleteDocumentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest): + 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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_document.UpdateDocumentRequest = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: document.ReloadDocumentRequest = None, + *, + name: str = None, + gcs_source: gcs.GcsSource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..a5d3edf67 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..f9ae67be5 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentsTransport +from .grpc import DocumentsGrpcTransport +from .grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] +_transport_registry['grpc'] = DocumentsGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport + +__all__ = ( + 'DocumentsTransport', + 'DocumentsGrpcTransport', + 'DocumentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..30922dcac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..3652aecf9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py @@ -0,0 +1,454 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + 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. + + 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'] + + +__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 new file mode 100644 index 000000000..108aa230c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py @@ -0,0 +1,458 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + 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. + + 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'] + + +__all__ = ( + 'DocumentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..82dfe86fd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..9e2f38eb8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py @@ -0,0 +1,1224 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, EntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: entity_type.ListEntityTypesRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesAsyncPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: entity_type.BatchUpdateEntityTypesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple entity types in the specified agent. + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest`): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: entity_type.BatchDeleteEntityTypesRequest = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entity types in the specified agent. Operation + + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates multiple new entities in the specified entity type. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entities in the specified entity type. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..4c402786f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py @@ -0,0 +1,1412 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EntityTypesTransport): + # transport is a EntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_entity_types(self, + request: entity_type.ListEntityTypesRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: entity_type.BatchUpdateEntityTypesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple entity types in the specified agent. + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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: entity_type.BatchDeleteEntityTypesRequest = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entity types in the specified agent. Operation + + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates multiple new entities in the specified entity type. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entities in the specified entity type. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..c943d32c2 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..1a2aa82dc --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EntityTypesTransport +from .grpc import EntityTypesGrpcTransport +from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] +_transport_registry['grpc'] = EntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'EntityTypesTransport', + 'EntityTypesGrpcTransport', + 'EntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..0068d90ec --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..9765d9e56 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py @@ -0,0 +1,519 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + Operation + + 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. Operation + + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__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 new file mode 100644 index 000000000..ac880bcf8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + Operation + + 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. Operation + + + 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. + + Operation + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..a3ad29ecd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..2591a9bee --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py @@ -0,0 +1,607 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.environments import pagers +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +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) + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: environment.ListEnvironmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsAsyncPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.ListEnvironmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + 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: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_environment(self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_environment_history(self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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 new file mode 100644 index 000000000..91782d01e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py @@ -0,0 +1,808 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.environments import pagers +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_environments(self, + request: environment.ListEnvironmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.ListEnvironmentsRequest. + # 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: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_environment(self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_environment_history(self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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 new file mode 100644 index 000000000..7419e474f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 new file mode 100644 index 000000000..fac90efe0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..289c1febf --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_environments(self) -> 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() + + +__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 new file mode 100644 index 000000000..848b7e0ac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py @@ -0,0 +1,393 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..1e54e25c4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,397 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..95fd359ef --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', +) diff --git a/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 new file mode 100644 index 000000000..fedbe1cc9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod(FulfillmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FulfillmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(FulfillmentsClient.parse_common_organization_path) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod(FulfillmentsClient.parse_common_project_path) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod(FulfillmentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """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: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest`): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = fulfillment.GetFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_fulfillment(self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest`): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2beta1.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsAsyncClient", +) diff --git a/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 new file mode 100644 index 000000000..759f1f7a0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py @@ -0,0 +1,535 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FulfillmentsTransport]: + """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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_fulfillment(self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_fulfillment(self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsClient", +) diff --git a/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 new file mode 100644 index 000000000..4b41f9212 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry['grpc'] = FulfillmentsGrpcTransport +_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + 'FulfillmentsTransport', + 'FulfillmentsGrpcTransport', + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..309c456bb --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, + default_timeout=None, + client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[ + fulfillment.Fulfillment, + Awaitable[fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[ + gcd_fulfillment.Fulfillment, + Awaitable[gcd_fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FulfillmentsTransport', +) diff --git a/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 new file mode 100644 index 000000000..cc48537f5 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + gcd_fulfillment.Fulfillment]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + +__all__ = ( + 'FulfillmentsGrpcTransport', +) diff --git a/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 new file mode 100644 index 000000000..48d5527df --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Awaitable[fulfillment.Fulfillment]]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment]]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + +__all__ = ( + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..8204500fb --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..6c4a7e568 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py @@ -0,0 +1,889 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, IntentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: intent.ListIntentsRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsAsyncPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListIntentsRequest`): + 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``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, + *, + intent: gcd_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: intent.DeleteIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or + indirect followup intents. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: intent.BatchUpdateIntentsRequest = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple intents in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes intents in the specified agent. + + Operation + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest`): + 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:`Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..ff9aed2ae --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py @@ -0,0 +1,1085 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, IntentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, IntentsTransport): + # transport is a IntentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_intents(self, + request: intent.ListIntentsRequest = None, + *, + parent: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListIntentsRequest): + 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``. + + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, + *, + name: str = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, + *, + intent: gcd_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: intent.DeleteIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or + indirect followup intents. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: intent.BatchUpdateIntentsRequest = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple intents in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes intents in the specified agent. + + Operation + + Args: + request (google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest): + 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 (Sequence[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); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..abacee624 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..aa8039bba --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import IntentsTransport +from .grpc import IntentsGrpcTransport +from .grpc_asyncio import IntentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] +_transport_registry['grpc'] = IntentsGrpcTransport +_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport + +__all__ = ( + 'IntentsTransport', + 'IntentsGrpcTransport', + 'IntentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..2fa4de0b4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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 new file mode 100644 index 000000000..cb885b248 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__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 new file mode 100644 index 000000000..58980cb8a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + """ + # Sanity 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. + + 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. + + 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. + + 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. + + Operation + + 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. + + Operation + + 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'] + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..670d8e66d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..4788424ac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py @@ -0,0 +1,615 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", + client_options: 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: knowledge_base.ListKnowledgeBasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: knowledge_base.GetKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..be6d1d63b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py @@ -0,0 +1,802 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KnowledgeBasesGrpcTransport +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, KnowledgeBasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, KnowledgeBasesTransport): + # transport is a KnowledgeBasesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_knowledge_bases(self, + request: knowledge_base.ListKnowledgeBasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: knowledge_base.GetKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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``. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..62df0fda9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..c04ef7c9f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import KnowledgeBasesTransport +from .grpc import KnowledgeBasesGrpcTransport +from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] +_transport_registry['grpc'] = KnowledgeBasesGrpcTransport +_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport + +__all__ = ( + 'KnowledgeBasesTransport', + 'KnowledgeBasesGrpcTransport', + 'KnowledgeBasesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..95390162e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..589bc3088 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..00d2ee830 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'KnowledgeBasesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..376e9e7d4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..5297b9b08 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py @@ -0,0 +1,1007 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.participants import pagers +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from google.cloud.dialogflow_v2beta1.types import session +from google.protobuf import field_mask_pb2 # 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 + + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, ParticipantsTransport] = "grpc_asyncio", + client_options: 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: gcd_participant.CreateParticipantRequest = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.ListParticipantsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsAsyncPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_participant.UpdateParticipantRequest = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest`): + 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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 + + async def suggest_articles(self, + request: participant.SuggestArticlesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.SuggestFaqAnswersRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.SuggestSmartRepliesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestSmartRepliesResponse: + r"""Gets smart replies for a participant based on + specific historical messages. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: participant.ListSuggestionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest`): + The request object. The request message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + + """ + # 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: participant.CompileSuggestionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest`): + The request object. The request message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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]. + + """ + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..f1ad0026b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py @@ -0,0 +1,1235 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.participants import pagers +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from google.cloud.dialogflow_v2beta1.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ParticipantsGrpcTransport +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ParticipantsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ParticipantsTransport): + # transport is a ParticipantsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_participant(self, + request: gcd_participant.CreateParticipantRequest = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.ListParticipantsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_participant.UpdateParticipantRequest = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 `__. + + Args: + request (google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest): + 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. + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 suggest_articles(self, + request: participant.SuggestArticlesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.SuggestFaqAnswersRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.SuggestSmartRepliesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestSmartRepliesResponse: + r"""Gets smart replies for a participant based on + specific historical messages. + + Args: + request (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: participant.ListSuggestionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest): + The request object. The request message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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. + + """ + # 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: participant.CompileSuggestionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest): + The request object. The request message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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]. + + """ + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..c5935440b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..e30c79b00 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ParticipantsTransport +from .grpc import ParticipantsGrpcTransport +from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] +_transport_registry['grpc'] = ParticipantsGrpcTransport +_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport + +__all__ = ( + 'ParticipantsTransport', + 'ParticipantsGrpcTransport', + 'ParticipantsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..ae1ce5066 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py @@ -0,0 +1,316 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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, + ), + } + + @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 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() + + +__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 new file mode 100644 index 000000000..a780256b3 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py @@ -0,0 +1,533 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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 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'] + + +__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 new file mode 100644 index 000000000..8921c8aaf --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py @@ -0,0 +1,537 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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'] + + +__all__ = ( + 'ParticipantsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..fb6678b14 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..91bf1d001 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py @@ -0,0 +1,649 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.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.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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: session_entity_type.ListSessionEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: session_entity_type.GetSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..8ccd7a69d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py @@ -0,0 +1,836 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.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.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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionEntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionEntityTypesTransport): + # transport is a SessionEntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_session_entity_types(self, + request: session_entity_type.ListSessionEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: session_entity_type.GetSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..b74bb17f0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 new file mode 100644 index 000000000..fee526724 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionEntityTypesTransport +from .grpc import SessionEntityTypesGrpcTransport +from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] +_transport_registry['grpc'] = SessionEntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'SessionEntityTypesTransport', + 'SessionEntityTypesGrpcTransport', + 'SessionEntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..617f495ec --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..d99649031 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 + + +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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'] + + +__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 new file mode 100644 index 000000000..75f33145b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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 +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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'] + + +__all__ = ( + 'SessionEntityTypesGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..92490cc5a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import 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 new file mode 100644 index 000000000..34b20dfac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py @@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.rpc import status_pb2 # 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, SessionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: gcd_session.DetectIntentRequest = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DetectIntentRequest`): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: AsyncIterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + 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 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. 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..0144f4441 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py @@ -0,0 +1,619 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionsTransport): + # transport is a SessionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def detect_intent(self, + request: gcd_session.DetectIntentRequest = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DetectIntentRequest): + 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. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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: Iterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + 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 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. 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "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 new file mode 100644 index 000000000..fde19f616 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionsTransport +from .grpc import SessionsGrpcTransport +from .grpc_asyncio import SessionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] +_transport_registry['grpc'] = SessionsGrpcTransport +_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport + +__all__ = ( + 'SessionsTransport', + 'SessionsGrpcTransport', + 'SessionsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..9a1bbb47f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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, + ), + } + + @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() + + +__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 new file mode 100644 index 000000000..3f18af46f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py @@ -0,0 +1,292 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def 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. + + 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). + + 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'] + + +__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 new file mode 100644 index 000000000..c3d48649c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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. + + 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). + + 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'] + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) 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 new file mode 100644 index 000000000..630246bde --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/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 new file mode 100644 index 000000000..4a52fb612 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py @@ -0,0 +1,641 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + """ + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + version_path = staticmethod(VersionsClient.version_path) + parse_version_path = staticmethod(VersionsClient.parse_version_path) + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """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: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.ListVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.GetVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcd_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.DeleteVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/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 new file mode 100644 index 000000000..21424201d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py @@ -0,0 +1,828 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """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 (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_versions(self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.ListVersionsRequest): + request = version.ListVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.GetVersionRequest): + request = version.GetVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.DeleteVersionRequest): + request = version.DeleteVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/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 new file mode 100644 index 000000000..436ffd3d9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflow_v2beta1.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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) -> AsyncIterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 new file mode 100644 index 000000000..dfb70ce95 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/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 new file mode 100644 index 000000000..53d755ba1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Union[ + version.ListVersionsResponse, + Awaitable[version.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/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 new file mode 100644 index 000000000..8e93cf2c8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/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 new file mode 100644 index 000000000..cf741b29a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,366 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Awaitable[version.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py new file mode 100644 index 000000000..9354cebac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .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 ( + 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, +) +from .conversation_event import ( + ConversationEvent, +) +from .conversation_profile import ( + AutomatedAgentConfig, + ConversationProfile, + CreateConversationProfileRequest, + DeleteConversationProfileRequest, + GetConversationProfileRequest, + HumanAgentAssistantConfig, + HumanAgentHandoffConfig, + ListConversationProfilesRequest, + ListConversationProfilesResponse, + LoggingConfig, + NotificationConfig, + UpdateConversationProfileRequest, +) +from .document import ( + CreateDocumentRequest, + DeleteDocumentRequest, + Document, + 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 ( + 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, + AutomatedAgentReply, + CompileSuggestionRequest, + CompileSuggestionResponse, + CreateParticipantRequest, + DtmfParameters, + FaqAnswer, + GetParticipantRequest, + ListParticipantsRequest, + ListParticipantsResponse, + ListSuggestionsRequest, + ListSuggestionsResponse, + Message, + MessageAnnotation, + OutputAudio, + Participant, + ResponseMessage, + SmartReplyAnswer, + 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', + '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', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + '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', + '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', + 'AutomatedAgentReply', + 'CompileSuggestionRequest', + 'CompileSuggestionResponse', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'ListSuggestionsRequest', + 'ListSuggestionsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'ResponseMessage', + 'SmartReplyAnswer', + '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 new file mode 100644 index 000000000..6d2a1c5ee --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py @@ -0,0 +1,492 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + '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 (Sequence[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. + """ + MATCH_MODE_UNSPECIFIED = 0 + MATCH_MODE_HYBRID = 1 + MATCH_MODE_ML_ONLY = 2 + + class ApiVersion(proto.Enum): + r"""API version for the agent.""" + 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.""" + TIER_UNSPECIFIED = 0 + TIER_STANDARD = 1 + TIER_ENTERPRISE = 2 + TIER_ENTERPRISE_PLUS = 3 + + parent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + enable_logging = proto.Field( + proto.BOOL, + number=8, + ) + match_mode = proto.Field( + proto.ENUM, + number=9, + enum=MatchMode, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=10, + ) + api_version = proto.Field( + proto.ENUM, + number=14, + enum=ApiVersion, + ) + tier = proto.Field( + proto.ENUM, + number=15, + enum=Tier, + ) + + +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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Agent', + ) + update_mask = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + environment = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchAgentsResponse(proto.Message): + r"""The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + + Attributes: + agents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Agent', + ) + next_page_token = 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 = 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + + 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``. + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class ImportAgentRequest(proto.Message): + r"""The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + + 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://". + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + + 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://". + agent_content (bytes): + Zip compressed raw byte content for agent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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 new file mode 100644 index 000000000..80dc99675 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py @@ -0,0 +1,392 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + answer_feedback = proto.Field( + proto.MESSAGE, + number=3, + message='AnswerFeedback', + ) + agent_assistant_record = proto.Field( + proto.MESSAGE, + number=4, + oneof='record', + message='AgentAssistantRecord', + ) + + +class AgentAssistantRecord(proto.Message): + r"""Represents a record of a human agent assistant answer. + Attributes: + article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): + Output only. The article suggestion answer. + faq_answer (google.cloud.dialogflow_v2beta1.types.FaqAnswer): + Output only. The FAQ answer. + """ + + article_suggestion_answer = proto.Field( + proto.MESSAGE, + number=5, + oneof='answer', + message=participant.ArticleAnswer, + ) + faq_answer = proto.Field( + proto.MESSAGE, + number=6, + oneof='answer', + message=participant.FaqAnswer, + ) + + +class AnswerFeedback(proto.Message): + r"""Represents feedback the customer has about the quality & + correctness of a certain answer in a conversation. + + 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. + 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.""" + CORRECTNESS_LEVEL_UNSPECIFIED = 0 + NOT_CORRECT = 1 + PARTIALLY_CORRECT = 2 + FULLY_CORRECT = 3 + + correctness_level = proto.Field( + proto.ENUM, + number=1, + enum=CorrectnessLevel, + ) + agent_assistant_detail_feedback = proto.Field( + proto.MESSAGE, + number=2, + oneof='detail_feedback', + message='AgentAssistantFeedback', + ) + clicked = proto.Field( + proto.BOOL, + number=3, + ) + click_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + displayed = proto.Field( + proto.BOOL, + number=4, + ) + display_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class AgentAssistantFeedback(proto.Message): + r"""Detail feedback of Agent Assistant result. + Attributes: + answer_relevance (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.AnswerRelevance): + Optional. Whether or not the suggested answer is relevant. + + 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.""" + ANSWER_RELEVANCE_UNSPECIFIED = 0 + IRRELEVANT = 1 + RELEVANT = 2 + + class DocumentCorrectness(proto.Enum): + r"""Correctness of document.""" + DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 + INCORRECT = 1 + CORRECT = 2 + + class DocumentEfficiency(proto.Enum): + r"""Efficiency of document.""" + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + submit_timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + summary_text = proto.Field( + proto.STRING, + number=3, + ) + + answer_relevance = proto.Field( + proto.ENUM, + number=1, + enum=AnswerRelevance, + ) + document_correctness = proto.Field( + proto.ENUM, + number=2, + enum=DocumentCorrectness, + ) + document_efficiency = proto.Field( + proto.ENUM, + number=3, + enum=DocumentEfficiency, + ) + summarization_feedback = proto.Field( + proto.MESSAGE, + number=4, + message=SummarizationFeedback, + ) + + +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 = 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/``. + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnswerRecordsResponse(proto.Message): + r"""Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + + Attributes: + answer_records (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + next_page_token = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + update_mask = 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 new file mode 100644 index 000000000..c020068e9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py @@ -0,0 +1,507 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + 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. + """ + 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. + """ + 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 `__. + """ + 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.""" + 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. + """ + 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 (Sequence[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 = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + +class SpeechWordInfo(proto.Message): + r"""Information for a word recognized by the speech recognizer. + Attributes: + word (str): + The word this info is for. + 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 = proto.Field( + proto.STRING, + number=3, + ) + start_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class InputAudioConfig(proto.Message): + 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 (Sequence[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 (Sequence[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. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechContext', + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + disable_no_speech_recognized_event = proto.Field( + proto.BOOL, + number=14, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + ssml_gender = proto.Field( + proto.ENUM, + number=2, + enum='SsmlVoiceGender', + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration of how speech should be synthesized. + Attributes: + speaking_rate (float): + Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 + 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 (Sequence[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 = proto.Field( + proto.DOUBLE, + number=1, + ) + pitch = proto.Field( + proto.DOUBLE, + number=2, + ) + volume_gain_db = proto.Field( + proto.DOUBLE, + number=3, + ) + effects_profile_id = proto.RepeatedField( + proto.STRING, + number=5, + ) + voice = proto.Field( + proto.MESSAGE, + number=4, + message='VoiceSelectionParams', + ) + + +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 = proto.Field( + proto.ENUM, + number=1, + enum='OutputAudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + synthesize_speech_config = proto.Field( + proto.MESSAGE, + number=3, + message='SynthesizeSpeechConfig', + ) + + +class TelephonyDtmfEvents(proto.Message): + r"""A wrapper of repeated TelephonyDtmf digits. + Attributes: + dtmf_events (Sequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): + A sequence of TelephonyDtmf digits. + """ + + dtmf_events = 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): + Optional. 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. + """ + + speech_model_variant = proto.Field( + proto.ENUM, + number=1, + enum='SpeechModelVariant', + ) + + +__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 new file mode 100644 index 000000000..a2943b2dd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import 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 = proto.Field( + proto.STRING, + number=1, + ) + lifespan_count = proto.Field( + proto.INT32, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ListContextsRequest(proto.Message): + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListContextsResponse(proto.Message): + r"""The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + + Attributes: + contexts (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Context', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Context', + ) + update_mask = 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 = 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 = 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 new file mode 100644 index 000000000..39b5ebd47 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -0,0 +1,462 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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', + }, +) + + +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.""" + 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 + """ + CONVERSATION_STAGE_UNSPECIFIED = 0 + VIRTUAL_AGENT_STAGE = 1 + HUMAN_ASSIST_STAGE = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + lifecycle_state = proto.Field( + proto.ENUM, + number=2, + enum=LifecycleState, + ) + conversation_profile = proto.Field( + proto.STRING, + number=3, + ) + phone_number = proto.Field( + proto.MESSAGE, + number=4, + message='ConversationPhoneNumber', + ) + conversation_stage = proto.Field( + proto.ENUM, + number=7, + enum=ConversationStage, + ) + start_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + conversation = proto.Field( + proto.MESSAGE, + number=2, + message='Conversation', + ) + conversation_id = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListConversationsResponse(proto.Message): + r"""The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + + Attributes: + conversations (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Conversation', + ) + next_page_token = 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 = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + requests = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateMessageRequest', + ) + + +class BatchCreateMessagesResponse(proto.Message): + r"""The request message for + [Conversations.BatchCreateMessagesResponse][]. + + Attributes: + messages (Sequence[google.cloud.dialogflow_v2beta1.types.Message]): + Messages created. + """ + + messages = 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 = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessagesResponse(proto.Message): + r"""The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + + Attributes: + messages (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=participant.Message, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__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 new file mode 100644 index 000000000..476880977 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + + 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. + """ + class Type(proto.Enum): + r"""Enumeration of the types of events available.""" + TYPE_UNSPECIFIED = 0 + CONVERSATION_STARTED = 1 + CONVERSATION_FINISHED = 2 + NEW_MESSAGE = 5 + UNRECOVERABLE_ERROR = 4 + + conversation = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + error_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + new_message_payload = 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 new file mode 100644 index 000000000..a3f7b6eec --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py @@ -0,0 +1,818 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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', + }, +) + + +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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + automated_agent_config = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentConfig', + ) + human_agent_assistant_config = proto.Field( + proto.MESSAGE, + number=4, + message='HumanAgentAssistantConfig', + ) + human_agent_handoff_config = proto.Field( + proto.MESSAGE, + number=5, + message='HumanAgentHandoffConfig', + ) + notification_config = proto.Field( + proto.MESSAGE, + number=6, + message='NotificationConfig', + ) + logging_config = proto.Field( + proto.MESSAGE, + number=7, + message='LoggingConfig', + ) + new_message_event_notification_config = proto.Field( + proto.MESSAGE, + number=8, + message='NotificationConfig', + ) + stt_config = proto.Field( + proto.MESSAGE, + number=9, + message=audio_config.SpeechToTextConfig, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + + +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 = 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 = proto.Field( + proto.BOOL, + number=1, + ) + only_end_user = proto.Field( + proto.BOOL, + number=2, + ) + + class SuggestionFeatureConfig(proto.Message): + r"""Config for suggestion features. + Attributes: + suggestion_feature (google.cloud.dialogflow_v2beta1.types.SuggestionFeature): + The suggestion feature. + 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. + """ + + suggestion_feature = proto.Field( + proto.MESSAGE, + number=5, + message=participant.SuggestionFeature, + ) + enable_event_based_suggestion = proto.Field( + proto.BOOL, + number=3, + ) + suggestion_trigger_settings = proto.Field( + proto.MESSAGE, + number=10, + message='HumanAgentAssistantConfig.SuggestionTriggerSettings', + ) + query_config = proto.Field( + proto.MESSAGE, + number=6, + message='HumanAgentAssistantConfig.SuggestionQueryConfig', + ) + conversation_model_config = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.ConversationModelConfig', + ) + + class SuggestionConfig(proto.Message): + r"""Detail human agent assistant config. + Attributes: + feature_configs (Sequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): + Configuration of different suggestion + 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 = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='HumanAgentAssistantConfig.SuggestionFeatureConfig', + ) + group_suggestion_responses = proto.Field( + proto.BOOL, + number=3, + ) + + class SuggestionQueryConfig(proto.Message): + r"""Config for suggestion query. + Attributes: + knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): + Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, + FAQ. + document_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): + Query from knowledge base document. It is used by: + SMART_REPLY, SMART_COMPOSE. + dialogflow_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): + Query from Dialogflow agent. It is used by + DIALOGFLOW_ASSIST. + 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 (Sequence[str]): + Required. Knowledge bases to query. Format: + ``projects//locations//knowledgeBases/``. + Currently, only one knowledge base is supported. + """ + + knowledge_bases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DocumentQuerySource(proto.Message): + r"""Document source settings. + + Supported features: SMART_REPLY, SMART_COMPOSE. + + Attributes: + documents (Sequence[str]): + Required. Knowledge documents to query from. Format: + ``projects//locations//knowledgeBases//documents/``. + Currently, only one document is supported. + """ + + documents = 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 = 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 = proto.Field( + proto.BOOL, + number=1, + ) + drop_virtual_agent_messages = proto.Field( + proto.BOOL, + number=2, + ) + drop_ivr_messages = proto.Field( + proto.BOOL, + number=3, + ) + + knowledge_base_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', + ) + document_query_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', + ) + dialogflow_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', + ) + max_results = proto.Field( + proto.INT32, + number=4, + ) + confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + context_filter_settings = 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. + + Attributes: + model (str): + Conversation model resource name. Format: + ``projects//conversationModels/``. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + 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 = proto.Field( + proto.BOOL, + number=2, + ) + enable_sentiment_analysis = proto.Field( + proto.BOOL, + number=3, + ) + + notification_config = proto.Field( + proto.MESSAGE, + number=2, + message='NotificationConfig', + ) + human_agent_suggestion_config = proto.Field( + proto.MESSAGE, + number=3, + message=SuggestionConfig, + ) + end_user_suggestion_config = proto.Field( + proto.MESSAGE, + number=4, + message=SuggestionConfig, + ) + message_analysis_config = proto.Field( + proto.MESSAGE, + number=5, + message=MessageAnalysisConfig, + ) + + +class HumanAgentHandoffConfig(proto.Message): + r"""Defines the hand off to a live agent, typically on which + external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. + + Attributes: + live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): + Uses LivePerson (https://www.liveperson.com). + salesforce_live_agent_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): + Uses Salesforce Live Agent. + """ + + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + deployment_id = proto.Field( + proto.STRING, + number=2, + ) + button_id = proto.Field( + proto.STRING, + number=3, + ) + endpoint_domain = proto.Field( + proto.STRING, + number=4, + ) + + live_person_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='agent_service', + message=LivePersonConfig, + ) + salesforce_live_agent_config = proto.Field( + proto.MESSAGE, + number=2, + 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. + + Notification works for phone calls, if this topic either 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. + + 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.""" + MESSAGE_FORMAT_UNSPECIFIED = 0 + PROTO = 1 + JSON = 2 + + topic = proto.Field( + proto.STRING, + number=1, + ) + message_format = proto.Field( + proto.ENUM, + number=2, + enum=MessageFormat, + ) + + +class LoggingConfig(proto.Message): + r"""Defines logging behavior for conversation lifecycle events. + Attributes: + enable_stackdriver_logging (bool): + Whether to log conversation events like + [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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationProfilesResponse(proto.Message): + r"""The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + + Attributes: + conversation_profiles (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + conversation_profile = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + update_mask = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +__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 new file mode 100644 index 000000000..c95fcdfef --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py @@ -0,0 +1,525 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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', + '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``. + + 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 (Sequence[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. + 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. + raw_content (bytes): + The raw content of the document. This field is only + permitted for EXTRACTIVE_QA and FAQ knowledge types. + 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_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 (Sequence[google.cloud.dialogflow_v2beta1.types.Document.MetadataEntry]): + 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. + """ + class KnowledgeType(proto.Enum): + r"""The knowledge type of document content.""" + KNOWLEDGE_TYPE_UNSPECIFIED = 0 + FAQ = 1 + EXTRACTIVE_QA = 2 + ARTICLE_SUGGESTION = 3 + SMART_REPLY = 4 + + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=4, + enum=KnowledgeType, + ) + content_uri = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + content = proto.Field( + proto.STRING, + number=6, + oneof='source', + ) + raw_content = proto.Field( + proto.BYTES, + number=9, + oneof='source', + ) + enable_auto_reload = proto.Field( + proto.BOOL, + number=11, + ) + latest_reload_status = proto.Field( + proto.MESSAGE, + number=12, + message=ReloadStatus, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + + Attributes: + documents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message='Document', + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=3, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + 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:////*.``. + 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 = proto.Field( + proto.STRING, + number=1, + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=gcs.GcsSources, + ) + document_template = proto.Field( + proto.MESSAGE, + number=3, + message='ImportDocumentTemplate', + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=4, + ) + + +class ImportDocumentTemplate(proto.Message): + r"""The template used for importing documents. + Attributes: + mime_type (str): + Required. The MIME type of the document. + knowledge_types (Sequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): + Required. The knowledge type of document + content. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Document.KnowledgeType', + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + Attributes: + warnings (Sequence[google.rpc.status_pb2.Status]): + Includes details about skipped documents or + any other warnings. + """ + + warnings = 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 = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Document', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class KnowledgeOperationMetadata(proto.Message): + r"""Metadata in google::longrunning::Operation for Knowledge + operations. + + Attributes: + state (google.cloud.dialogflow_v2beta1.types.KnowledgeOperationMetadata.State): + Required. Output only. The current state of + this operation. + """ + class State(proto.Enum): + r"""States of the operation.""" + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + DONE = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + + +class ReloadDocumentRequest(proto.Message): + r"""Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. + + 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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message=gcs.GcsSource, + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=4, + ) + + +__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 new file mode 100644 index 000000000..ff36c8fdd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py @@ -0,0 +1,586 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + '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 (Sequence[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.""" + 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). + """ + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Entity, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='EntityType', + ) + language_code = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_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 = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + 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://". + entity_type_batch_inline (google.cloud.dialogflow_v2beta1.types.EntityTypeBatch): + The collection of entity types 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='entity_type_batch', + ) + entity_type_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='entity_type_batch', + message='EntityTypeBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): + The collection of updated or created entity + types. + """ + + entity_types = 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 (Sequence[str]): + Required. The names entity types to delete. All names must + point to the same agent as ``parent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_names = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + entity_values = proto.RepeatedField( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class EntityTypeBatch(proto.Message): + r"""This message is a wrapper around a collection of entity + types. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): + A collection of entity types. + """ + + entity_types = 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 new file mode 100644 index 000000000..2142e07f6 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + """ + STATE_UNSPECIFIED = 0 + STOPPED = 1 + LOADING = 2 + RUNNING = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + agent_version = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + text_to_speech_settings = proto.Field( + proto.MESSAGE, + number=7, + message='TextToSpeechSettings', + ) + fulfillment = proto.Field( + proto.MESSAGE, + number=8, + message=gcd_fulfillment.Fulfillment, + ) + + +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 (Sequence[google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ + + enable_text_to_speech = proto.Field( + proto.BOOL, + number=1, + ) + output_audio_encoding = proto.Field( + proto.ENUM, + number=2, + enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=3, + ) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) + + +class ListEnvironmentsRequest(proto.Message): + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + environment_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2beta1.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self + + parent = proto.Field( + proto.STRING, + number=1, + ) + entries = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Entry, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py new file mode 100644 index 000000000..8a35fc7c4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + }, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + The human-readable name of the fulfillment, + unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + enabled (bool): + Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature]): + The field defines whether the fulfillment is + enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + The user name for HTTP Basic authentication. + password (str): + The password for HTTP Basic authentication. + request_headers (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + The HTTP request headers to send together + with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + username = proto.Field( + proto.STRING, + number=2, + ) + password = proto.Field( + proto.STRING, + number=3, + ) + request_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + is_cloud_function = proto.Field( + proto.BOOL, + number=5, + ) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + Attributes: + type_ (google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Fulfillment.Feature.Type', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=3, + oneof='fulfillment', + message=GenericWebService, + ) + enabled = proto.Field( + proto.BOOL, + number=4, + ) + features = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Feature, + ) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field( + proto.MESSAGE, + number=1, + message='Fulfillment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py new file mode 100644 index 000000000..2f44f0d8d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'GcsSources', + 'GcsSource', + }, +) + + +class GcsSources(proto.Message): + r"""Google Cloud Storage locations for the inputs. + Attributes: + uris (Sequence[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 = 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 = 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 new file mode 100644 index 000000000..0473ecffe --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.STRING, + number=3, + ) + suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_participant.SuggestionResult, + ) + + +__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 new file mode 100644 index 000000000..69452e9d1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py @@ -0,0 +1,2124 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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. + """ + 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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Parameter]): + Optional. The collection of parameters + associated with the intent. + messages (Sequence[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 (Sequence[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 (Sequence[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.""" + 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 (Sequence[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.""" + 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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + alias = proto.Field( + proto.STRING, + number=3, + ) + user_defined = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='Intent.TrainingPhrase.Type', + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Intent.TrainingPhrase.Part', + ) + times_added_count = proto.Field( + proto.INT32, + number=4, + ) + + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + default_value = proto.Field( + proto.STRING, + number=4, + ) + entity_type_display_name = proto.Field( + proto.STRING, + number=5, + ) + mandatory = proto.Field( + proto.BOOL, + number=6, + ) + prompts = proto.RepeatedField( + proto.STRING, + number=7, + ) + is_list = proto.Field( + proto.BOOL, + number=8, + ) + + class Message(proto.Message): + r"""Corresponds to the ``Response`` field in the Dialogflow console. + Attributes: + text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): + Returns a text response. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Displays an image. + quick_replies (google.cloud.dialogflow_v2beta1.types.Intent.Message.QuickReplies): + Displays quick replies. + card (google.cloud.dialogflow_v2beta1.types.Intent.Message.Card): + Displays a card. + payload (google.protobuf.struct_pb2.Struct): + A custom platform-specific response. + simple_responses (google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponses): + Returns a voice or text-only response for + Actions on Google. + basic_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard): + Displays a basic card for Actions on Google. + suggestions (google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestions): + Displays suggestion chips for Actions on + Google. + link_out_suggestion (google.cloud.dialogflow_v2beta1.types.Intent.Message.LinkOutSuggestion): + Displays a link out suggestion chip for + Actions on Google. + list_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect): + Displays a list card for Actions on Google. + carousel_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect): + Displays a carousel card for Actions on + Google. + telephony_play_audio (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyPlayAudio): + Plays audio from a file in Telephony Gateway. + telephony_synthesize_speech (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonySynthesizeSpeech): + Synthesizes speech in Telephony Gateway. + telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyTransferCall): + Transfers the call in Telephony Gateway. + 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. + rbm_standalone_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard): + Standalone Rich Business Messaging (RBM) rich + card response. + rbm_carousel_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard): + Rich Business Messaging (RBM) carousel rich + card response. + browse_carousel_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard): + Browse carousel card for Actions on Google. + table_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCard): + Table card for Actions on Google. + media_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent): + The media content card for Actions on Google. + 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. + """ + 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 (Sequence[str]): + Optional. The collection of the agent's + responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Image(proto.Message): + r"""The image response message. + Attributes: + image_uri (str): + Optional. The public URI to an image file. + 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 = proto.Field( + proto.STRING, + number=1, + ) + accessibility_text = proto.Field( + proto.STRING, + number=2, + ) + + class QuickReplies(proto.Message): + r"""The quick replies response message. + Attributes: + title (str): + Optional. The title of the collection of + quick replies. + quick_replies (Sequence[str]): + Optional. The collection of quick replies. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + quick_replies = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Card(proto.Message): + r"""The card response message. + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + image_uri (str): + Optional. The public URI to an image file for + the card. + buttons (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + postback = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image_uri = proto.Field( + proto.STRING, + number=3, + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.Card.Button', + ) + + class SimpleResponse(proto.Message): + r"""The simple response message containing speech or text. + Attributes: + text_to_speech (str): + One of text_to_speech or ssml must be provided. The plain + 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 = proto.Field( + proto.STRING, + number=1, + ) + ssml = proto.Field( + proto.STRING, + number=2, + ) + display_text = proto.Field( + proto.STRING, + number=3, + ) + + class SimpleResponses(proto.Message): + r"""The collection of simple response candidates. This message in + ``QueryResult.fulfillment_messages`` and + ``WebhookResponse.fulfillment_messages`` should contain only one + ``SimpleResponse``. + + Attributes: + simple_responses (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponse]): + Required. The list of simple responses. + """ + + simple_responses = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + open_uri_action = proto.Field( + proto.MESSAGE, + number=2, + message='Intent.Message.BasicCard.Button.OpenUriAction', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + formatted_text = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + buttons = 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 = proto.Field( + proto.STRING, + number=1, + ) + + class Suggestions(proto.Message): + r"""The collection of suggestions. + Attributes: + suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): + Required. The list of suggested replies. + """ + + suggestions = 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 = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + + class ListSelect(proto.Message): + r"""The card for presenting a list of options to select from. + Attributes: + title (str): + Optional. The overall title of the list. + items (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + items = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.ListSelect.Item', + ) + subtitle = proto.Field( + proto.STRING, + number=3, + ) + + class CarouselSelect(proto.Message): + r"""The card for presenting a carousel of options to select from. + Attributes: + items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): + Required. Carousel items. + """ + + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + items = 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 (Sequence[str]): + Optional. A list of synonyms that can also be + used to trigger this item in dialog. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class TelephonyPlayAudio(proto.Message): + r"""Plays audio from a file in Telephony Gateway. + Attributes: + audio_uri (str): + Required. URI to a Google Cloud Storage object containing + 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 = 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. + + Attributes: + text (str): + The raw text to be synthesized. + ssml (str): + The SSML to be synthesized. For more information, see + `SSML `__. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + ssml = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + + class TelephonyTransferCall(proto.Message): + r"""Transfers the call in Telephony Gateway. + Attributes: + phone_number (str): + Required. The phone number to transfer the call to in `E.164 + format `__. + + We currently only allow transferring to US numbers + (+1xxxyyyzzzz). + """ + + phone_number = proto.Field( + proto.STRING, + number=1, + ) + + class RbmText(proto.Message): + r"""Rich Business Messaging (RBM) text response with suggestions. + Attributes: + text (str): + Required. Text sent and displayed to the + user. + rbm_suggestion (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): + Optional. One or more suggestions to show to + the user. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + rbm_suggestion = 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 (Sequence[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.""" + CARD_WIDTH_UNSPECIFIED = 0 + SMALL = 1 + MEDIUM = 2 + + card_width = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.RbmCarouselCard.CardWidth', + ) + card_contents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.RbmCardContent', + ) + + 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.""" + CARD_ORIENTATION_UNSPECIFIED = 0 + HORIZONTAL = 1 + VERTICAL = 2 + + class ThumbnailImageAlignment(proto.Enum): + r"""Thumbnail preview alignment for standalone cards with + horizontal layout. + """ + THUMBNAIL_IMAGE_ALIGNMENT_UNSPECIFIED = 0 + LEFT = 1 + RIGHT = 2 + + card_orientation = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.RbmStandaloneCard.CardOrientation', + ) + thumbnail_image_alignment = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment', + ) + card_content = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.RbmCardContent', + ) + + class RbmCardContent(proto.Message): + r"""Rich Business Messaging (RBM) Card content + Attributes: + title (str): + Optional. Title of the card (at most 200 + 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 (Sequence[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""" + HEIGHT_UNSPECIFIED = 0 + SHORT = 1 + MEDIUM = 2 + TALL = 3 + + file_uri = proto.Field( + proto.STRING, + number=1, + ) + thumbnail_uri = proto.Field( + proto.STRING, + number=2, + ) + height = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.RbmCardContent.RbmMedia.Height', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + media = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.RbmCardContent.RbmMedia', + ) + suggestions = 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). + + Attributes: + reply (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedReply): + Predefined replies for user to select instead + of typing + action (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction): + Predefined client side actions that user can + choose + """ + + reply = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion', + message='Intent.Message.RbmSuggestedReply', + ) + action = 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 = proto.Field( + proto.STRING, + number=1, + ) + postback_data = proto.Field( + proto.STRING, + number=2, + ) + + class RbmSuggestedAction(proto.Message): + r"""Rich Business Messaging (RBM) suggested client-side action + that the user can choose from the card. + + 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 + open_url (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri): + Suggested client side action: Open a URI on + device + share_location (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation): + Suggested client side action: Share user + location + """ + + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + + class RbmSuggestedActionShareLocation(proto.Message): + r"""Opens the device's location chooser so the user can pick a + location to send back to the agent. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + postback_data = proto.Field( + proto.STRING, + number=2, + ) + dial = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial', + ) + open_url = proto.Field( + proto.MESSAGE, + number=4, + oneof='action', + message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri', + ) + share_location = proto.Field( + proto.MESSAGE, + number=5, + 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaObject]): + Required. List of media objects. + """ + class ResponseMediaType(proto.Enum): + r"""Format of response media type.""" + RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + + class ResponseMediaObject(proto.Message): + r"""Response media object for media content card. + 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. + icon (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. Icon to display above media + content. + content_url (str): + Required. Url where the media is stored. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + large_image = proto.Field( + proto.MESSAGE, + number=3, + oneof='image', + message='Intent.Message.Image', + ) + icon = proto.Field( + proto.MESSAGE, + number=4, + oneof='image', + message='Intent.Message.Image', + ) + content_url = proto.Field( + proto.STRING, + number=5, + ) + + media_type = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.MediaContent.ResponseMediaType', + ) + media_objects = 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 (Sequence[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. + """ + 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.""" + URL_TYPE_HINT_UNSPECIFIED = 0 + AMP_ACTION = 1 + AMP_CONTENT = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + url_type_hint = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', + ) + + open_uri_action = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + footer = proto.Field( + proto.STRING, + number=5, + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', + ) + image_display_options = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties]): + Optional. Display properties for the columns + in this table. + rows (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardRow]): + Optional. Rows in this table of data. + buttons (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): + Optional. List of buttons for the card. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.Image', + ) + column_properties = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.ColumnProperties', + ) + rows = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.TableCardRow', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Intent.Message.BasicCard.Button', + ) + + 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.""" + HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 + LEADING = 1 + CENTER = 2 + TRAILING = 3 + + header = proto.Field( + proto.STRING, + number=1, + ) + horizontal_alignment = 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 (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.TableCardCell', + ) + divider_after = 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 = proto.Field( + proto.STRING, + number=1, + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='Intent.Message.Text', + ) + image = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Intent.Message.Image', + ) + quick_replies = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message='Intent.Message.QuickReplies', + ) + card = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message='Intent.Message.Card', + ) + payload = proto.Field( + proto.MESSAGE, + number=5, + oneof='message', + message=struct_pb2.Struct, + ) + simple_responses = proto.Field( + proto.MESSAGE, + number=7, + oneof='message', + message='Intent.Message.SimpleResponses', + ) + basic_card = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message='Intent.Message.BasicCard', + ) + suggestions = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message='Intent.Message.Suggestions', + ) + link_out_suggestion = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message='Intent.Message.LinkOutSuggestion', + ) + list_select = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message='Intent.Message.ListSelect', + ) + carousel_select = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message='Intent.Message.CarouselSelect', + ) + telephony_play_audio = proto.Field( + proto.MESSAGE, + number=13, + oneof='message', + message='Intent.Message.TelephonyPlayAudio', + ) + telephony_synthesize_speech = proto.Field( + proto.MESSAGE, + number=14, + oneof='message', + message='Intent.Message.TelephonySynthesizeSpeech', + ) + telephony_transfer_call = proto.Field( + proto.MESSAGE, + number=15, + oneof='message', + message='Intent.Message.TelephonyTransferCall', + ) + rbm_text = proto.Field( + proto.MESSAGE, + number=18, + oneof='message', + message='Intent.Message.RbmText', + ) + rbm_standalone_rich_card = proto.Field( + proto.MESSAGE, + number=19, + oneof='message', + message='Intent.Message.RbmStandaloneCard', + ) + rbm_carousel_rich_card = proto.Field( + proto.MESSAGE, + number=20, + oneof='message', + message='Intent.Message.RbmCarouselCard', + ) + browse_carousel_card = proto.Field( + proto.MESSAGE, + number=22, + oneof='message', + message='Intent.Message.BrowseCarouselCard', + ) + table_card = proto.Field( + proto.MESSAGE, + number=23, + oneof='message', + message='Intent.Message.TableCard', + ) + media_content = proto.Field( + proto.MESSAGE, + number=24, + oneof='message', + message='Intent.Message.MediaContent', + ) + platform = proto.Field( + proto.ENUM, + number=6, + enum='Intent.Message.Platform', + ) + + class FollowupIntentInfo(proto.Message): + r"""Represents a single followup intent in the chain. + Attributes: + followup_intent_name (str): + The unique identifier of the followup intent. Format: + ``projects//agent/intents/``. + parent_followup_intent_name (str): + The unique identifier of the followup intent's parent. + Format: ``projects//agent/intents/``. + """ + + followup_intent_name = proto.Field( + proto.STRING, + number=1, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + webhook_state = proto.Field( + proto.ENUM, + number=6, + enum=WebhookState, + ) + priority = proto.Field( + proto.INT32, + number=3, + ) + is_fallback = proto.Field( + proto.BOOL, + number=4, + ) + ml_enabled = proto.Field( + proto.BOOL, + number=5, + ) + ml_disabled = proto.Field( + proto.BOOL, + number=19, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=20, + ) + end_interaction = proto.Field( + proto.BOOL, + number=21, + ) + input_context_names = proto.RepeatedField( + proto.STRING, + number=7, + ) + events = proto.RepeatedField( + proto.STRING, + number=8, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=TrainingPhrase, + ) + action = proto.Field( + proto.STRING, + number=10, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=12, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Parameter, + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=Message, + ) + default_response_platforms = proto.RepeatedField( + proto.ENUM, + number=15, + enum=Message.Platform, + ) + root_followup_intent_name = proto.Field( + proto.STRING, + number=16, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=17, + ) + followup_intent_info = 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``. + 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + + Attributes: + intents (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = 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 = proto.Field( + proto.STRING, + number=1, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + intent_view = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + intent_view = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateIntentsRequest(proto.Message): + r"""The request message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + + 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://". + intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): + The collection of intents 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. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='intent_batch', + ) + intent_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='intent_batch', + message='IntentBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + intent_view = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + The collection of updated or created intents. + """ + + intents = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + Required. The collection of intents to delete. Only intent + ``name`` must be filled in. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent', + ) + + +class IntentBatch(proto.Message): + r"""This message is a wrapper around a collection of intents. + Attributes: + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + A collection of intents. + """ + + intents = 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 new file mode 100644 index 000000000..dca009b2d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + '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 = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKnowledgeBasesRequest(proto.Message): + 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKnowledgeBasesResponse(proto.Message): + r"""Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + knowledge_bases (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + knowledge_base = 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 = proto.Field( + proto.STRING, + number=1, + ) + force = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + update_mask = 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 new file mode 100644 index 000000000..90b5a7b46 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py @@ -0,0 +1,1473 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflow_v2beta1.types import 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', + 'OutputAudio', + 'AutomatedAgentReply', + 'SuggestionFeature', + 'AnalyzeContentRequest', + 'DtmfParameters', + 'AnalyzeContentResponse', + '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. + """ + class Role(proto.Enum): + r"""Enumeration of the roles a participant can play in a + conversation. + """ + ROLE_UNSPECIFIED = 0 + HUMAN_AGENT = 1 + AUTOMATED_AGENT = 2 + END_USER = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + role = proto.Field( + proto.ENUM, + number=2, + enum=Role, + ) + obfuscated_external_user_id = proto.Field( + proto.STRING, + number=7, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + content = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + participant = proto.Field( + proto.STRING, + number=4, + ) + participant_role = proto.Field( + proto.ENUM, + number=5, + enum='Participant.Role', + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + send_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + message_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='MessageAnnotation', + ) + sentiment_analysis = proto.Field( + proto.MESSAGE, + number=8, + message=session.SentimentAnalysisResult, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListParticipantsResponse(proto.Message): + r"""The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + + Attributes: + participants (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Participant', + ) + next_page_token = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Participant', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +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 = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.OutputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class AutomatedAgentReply(proto.Message): + r"""Represents a response from an automated agent. + Attributes: + detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): + Response of the Dialogflow + [Sessions.DetectIntent][google.cloud.dialogflow.v2beta1.Sessions.DetectIntent] + call. + response_messages (Sequence[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/``. + event (str): + Event name if an event is triggered for the + query. + cx_session_parameters (google.protobuf.struct_pb2.Struct): + The collection of current Dialogflow CX agent + session parameters at the time of this response. + """ + + detect_intent_response = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message=session.DetectIntentResponse, + ) + response_messages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ResponseMessage', + ) + intent = proto.Field( + proto.STRING, + number=4, + oneof='match', + ) + event = proto.Field( + proto.STRING, + number=5, + oneof='match', + ) + cx_session_parameters = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +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.""" + TYPE_UNSPECIFIED = 0 + ARTICLE_SUGGESTION = 1 + FAQ = 2 + SMART_REPLY = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + + +class AnalyzeContentRequest(proto.Message): + r"""The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + + 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. + event_input (google.cloud.dialogflow_v2beta1.types.EventInput): + An input event to send to Dialogflow. + 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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + text_input = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message=session.TextInput, + ) + event_input = proto.Field( + proto.MESSAGE, + number=8, + oneof='input', + message=session.EventInput, + ) + reply_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + query_params = proto.Field( + proto.MESSAGE, + number=9, + message=session.QueryParameters, + ) + message_send_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + request_id = 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 = 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 (Sequence[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 (Sequence[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. + """ + + reply_text = proto.Field( + proto.STRING, + number=1, + ) + reply_audio = proto.Field( + proto.MESSAGE, + number=2, + message='OutputAudio', + ) + automated_agent_reply = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentReply', + ) + message = proto.Field( + proto.MESSAGE, + number=5, + message='Message', + ) + human_agent_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='SuggestionResult', + ) + end_user_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='SuggestionResult', + ) + dtmf_parameters = proto.Field( + proto.MESSAGE, + number=9, + message='DtmfParameters', + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + formatted_value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + +class MessageAnnotation(proto.Message): + r"""Represents the result of annotation for the message. + Attributes: + parts (Sequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): + Optional. The collection of annotated message parts ordered + 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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnnotatedMessagePart', + ) + contain_entities = 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 (Sequence[str]): + Output only. Article snippets. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ArticleAnswer.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class FaqAnswer(proto.Message): + r"""Represents answer from "frequently asked questions". + Attributes: + answer (str): + The piece of text from the ``source`` knowledge base + 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 (Sequence[google.cloud.dialogflow_v2beta1.types.FaqAnswer.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class SmartReplyAnswer(proto.Message): + r"""Represents a smart reply answer. + Attributes: + reply (str): + The content of the reply. + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + answer_record = proto.Field( + proto.STRING, + number=3, + ) + + +class SuggestionResult(proto.Message): + 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]. + + Attributes: + error (google.rpc.status_pb2.Status): + Error status if the request failed. + suggest_articles_response (google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse): + SuggestArticlesResponse if request is for + ARTICLE_SUGGESTION. + suggest_faq_answers_response (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse): + SuggestFaqAnswersResponse if request is for FAQ_ANSWER. + suggest_smart_replies_response (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse): + SuggestSmartRepliesResponse if request is for SMART_REPLY. + """ + + error = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion_response', + message=status_pb2.Status, + ) + suggest_articles_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='suggestion_response', + message='SuggestArticlesResponse', + ) + suggest_faq_answers_response = proto.Field( + proto.MESSAGE, + number=3, + oneof='suggestion_response', + message='SuggestFaqAnswersResponse', + ) + suggest_smart_replies_response = proto.Field( + proto.MESSAGE, + number=4, + 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestArticlesResponse(proto.Message): + r"""The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + + Attributes: + article_answers (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ArticleAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = 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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestFaqAnswersResponse(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + + Attributes: + faq_answers (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FaqAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = 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 = proto.Field( + proto.STRING, + number=1, + ) + current_text_input = proto.Field( + proto.MESSAGE, + number=4, + message=session.TextInput, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestSmartRepliesResponse(proto.Message): + r"""The response message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + + Attributes: + smart_reply_answers (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SmartReplyAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class Suggestion(proto.Message): + r"""Represents a suggestion for a human agent. + Attributes: + name (str): + Output only. The name of this suggestion. Format: + ``projects//locations//conversations//participants/*/suggestions/``. + articles (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article]): + Output only. Articles ordered by score in + descending order. + faq_answers (Sequence[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 (Sequence[str]): + Output only. Article snippets. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + class FaqAnswer(proto.Message): + r"""Represents suggested answer from "frequently asked + 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.FaqAnswer.MetadataEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + articles = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Article, + ) + faq_answers = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=FaqAnswer, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + latest_message = 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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSuggestionsResponse(proto.Message): + r"""The response message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + + Attributes: + suggestions (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Suggestion', + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class CompileSuggestionResponse(proto.Message): + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Suggestion', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ResponseMessage(proto.Message): + r"""Response messages from an automated agent. + Attributes: + text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): + Returns a text response. + payload (google.protobuf.struct_pb2.Struct): + Returns a response containing a custom, + platform-specific payload. + live_agent_handoff (google.cloud.dialogflow_v2beta1.types.ResponseMessage.LiveAgentHandoff): + Hands off conversation to a live agent. + end_interaction (google.cloud.dialogflow_v2beta1.types.ResponseMessage.EndInteraction): + A signal that indicates the interaction with + the Dialogflow agent has ended. + """ + + class Text(proto.Message): + r"""The text response message. + Attributes: + text (Sequence[str]): + A collection of text responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. + """ + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message=Text, + ) + payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message=struct_pb2.Struct, + ) + live_agent_handoff = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message=LiveAgentHandoff, + ) + end_interaction = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message=EndInteraction, + ) + + +__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 new file mode 100644 index 000000000..f63b3eb9c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py @@ -0,0 +1,1151 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=5, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + Attributes: + response_id (str): + The unique identifier of the response. It can + 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message='QueryResult', + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = 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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2beta1.types.QueryParameters.WebhookHeadersEntry]): + 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 = proto.Field( + proto.STRING, + number=1, + ) + geo_location = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + contexts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=4, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + knowledge_base_names = proto.RepeatedField( + proto.STRING, + number=12, + ) + sentiment_analysis_request_config = proto.Field( + proto.MESSAGE, + number=10, + message='SentimentAnalysisRequestConfig', + ) + sub_agents = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=agent.SubAgent, + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +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. + + Attributes: + audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): + Instructs the speech recognizer how to + process the speech audio. + text (google.cloud.dialogflow_v2beta1.types.TextInput): + The natural language text to be processed. + event (google.cloud.dialogflow_v2beta1.types.EventInput): + The event to be processed. + dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): + The DTMF digits used to invoke intent and + fill in parameter value. + """ + + audio_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='input', + message=gcd_audio_config.InputAudioConfig, + ) + text = proto.Field( + proto.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + event = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='EventInput', + ) + dtmf = proto.Field( + proto.MESSAGE, + number=4, + 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. + 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 (Sequence[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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + speech_recognition_confidence = proto.Field( + proto.FLOAT, + number=2, + ) + action = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + all_required_params_present = proto.Field( + proto.BOOL, + number=5, + ) + fulfillment_text = proto.Field( + proto.STRING, + number=6, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, + ) + webhook_source = proto.Field( + proto.STRING, + number=8, + ) + webhook_payload = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=context.Context, + ) + intent = proto.Field( + proto.MESSAGE, + number=11, + message=gcd_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=12, + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=14, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=17, + message='SentimentAnalysisResult', + ) + knowledge_answers = proto.Field( + proto.MESSAGE, + number=18, + message='KnowledgeAnswers', + ) + + +class KnowledgeAnswers(proto.Message): + r"""Represents the result of querying a Knowledge base. + Attributes: + answers (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): + A list of answers from Knowledge Connector. + """ + + 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. + """ + MATCH_CONFIDENCE_LEVEL_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + + source = proto.Field( + proto.STRING, + number=1, + ) + faq_question = proto.Field( + proto.STRING, + number=2, + ) + answer = proto.Field( + proto.STRING, + number=3, + ) + match_confidence_level = proto.Field( + proto.ENUM, + number=4, + enum='KnowledgeAnswers.Answer.MatchConfidenceLevel', + ) + match_confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + answers = 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 = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + single_utterance = proto.Field( + proto.BOOL, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = 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 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. 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + recognition_result = proto.Field( + proto.MESSAGE, + number=2, + message='StreamingRecognitionResult', + ) + query_result = proto.Field( + proto.MESSAGE, + number=3, + message='QueryResult', + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=5, + ) + output_audio_config = 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. + + Example: + + 1. transcript: "tube" + + 2. transcript: "to be a" + + 3. transcript: "to be" + + 4. transcript: "to be or not to be" is_final: true + + 5. transcript: " that's" + + 6. transcript: " that is" + + 7. message_type: ``END_OF_SINGLE_UTTERANCE`` + + 8. transcript: " that is the question" is_final: true + + Only two of the responses contain final results (#4 and #8 indicated + by ``is_final: true``). Concatenating these generates the full + transcript: "to be or not to be that is the question". + + In each response we populate: + + - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. + + - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. + + 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 (Sequence[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``. + 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.""" + MESSAGE_TYPE_UNSPECIFIED = 0 + TRANSCRIPT = 1 + END_OF_SINGLE_UTTERANCE = 2 + + message_type = proto.Field( + proto.ENUM, + number=1, + enum=MessageType, + ) + transcript = proto.Field( + proto.STRING, + number=2, + ) + is_final = proto.Field( + proto.BOOL, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + stability = proto.Field( + proto.FLOAT, + number=6, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + dtmf_digits = 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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + language_code = 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class SentimentAnalysisRequestConfig(proto.Message): + r"""Configures the types of sentiment analysis to perform. + Attributes: + analyze_query_text_sentiment (bool): + Instructs the service to perform sentiment analysis on + ``query_text``. If not provided, sentiment analysis is not + performed on ``query_text``. + """ + + analyze_query_text_sentiment = 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 = 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. + + 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 = proto.Field( + proto.FLOAT, + number=1, + ) + magnitude = 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 new file mode 100644 index 000000000..4442b9004 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 (Sequence[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.""" + ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 + ENTITY_OVERRIDE_MODE_OVERRIDE = 1 + ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + entity_override_mode = proto.Field( + proto.ENUM, + number=2, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=entity_type.EntityType.Entity, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + next_page_token = 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + session_entity_type = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + update_mask = 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 = 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 new file mode 100644 index 000000000..9e80a2e22 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__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 (Sequence[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 messsage. + """ + class Severity(proto.Enum): + r"""Represents a level of severity.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + CRITICAL = 4 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + entries = proto.RepeatedField( + proto.STRING, + number=3, + ) + error_message = proto.Field( + proto.STRING, + number=4, + ) + + +class ValidationResult(proto.Message): + r"""Represents the output of agent validation. + Attributes: + validation_errors (Sequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): + Contains all validation errors. + """ + + validation_errors = 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 new file mode 100644 index 000000000..c1795217f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2beta1.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + version_number = proto.Field( + proto.INT32, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.ENUM, + number=6, + enum=VersionStatus, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2beta1.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Version', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field( + proto.MESSAGE, + number=1, + message='Version', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py new file mode 100644 index 000000000..2d91bd504 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.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 (Sequence[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 = proto.Field( + proto.STRING, + number=4, + ) + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.QueryResult, + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_session.QueryResult, + ) + original_detect_intent_request = proto.Field( + proto.MESSAGE, + number=3, + message='OriginalDetectIntentRequest', + ) + + +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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=intent.Intent.Message, + ) + source = proto.Field( + proto.STRING, + number=3, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=context.Context, + ) + followup_event_input = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_session.EventInput, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=7, + ) + end_interaction = proto.Field( + proto.BOOL, + number=8, + ) + session_entity_types = 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 = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + payload = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/mypy.ini b/owl-bot-staging/v2beta1/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/owl-bot-staging/v2beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2beta1/noxfile.py b/owl-bot-staging/v2beta1/noxfile.py new file mode 100644 index 000000000..7c973f2b5 --- /dev/null +++ b/owl-bot-staging/v2beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/dialogflow_v2beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) diff --git a/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py b/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py new file mode 100644 index 000000000..0a8e20f0b --- /dev/null +++ b/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py @@ -0,0 +1,263 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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', 'message_send_time', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_create_messages': ('parent', 'requests', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_answer_record': ('name', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), + 'list_answer_records': ('parent', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + 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: not a.keyword.value 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 new file mode 100644 index 000000000..4601e7528 --- /dev/null +++ b/owl-bot-staging/v2beta1/setup.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-dialogflow', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2beta1/tests/__init__.py b/owl-bot-staging/v2beta1/tests/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta1/tests/unit/__init__.py b/owl-bot-staging/v2beta1/tests/unit/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/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 new file mode 100644 index 000000000..9f0518ac0 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py @@ -0,0 +1,3145 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.agents import AgentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.agents import AgentsClient +from google.cloud.dialogflow_v2beta1.services.agents import pagers +from google.cloud.dialogflow_v2beta1.services.agents import transports +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_client_get_transport_class(): + transport = AgentsClient.get_transport_class() + available_transports = [ + transports.AgentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): + 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.2552, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +def test_get_agent_from_dict(): + test_get_agent(request_type=dict) + + +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.2552, + 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.2552, 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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): + 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.2552, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + ) + response = client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +def test_set_agent_from_dict(): + test_set_agent(request_type=dict) + + +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.2552, + 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.2552, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +@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 = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = gcd_agent.Agent() + client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=agent.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 = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + 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=agent.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] + assert args[0].agent == gcd_agent.Agent(parent='parent_value') + + +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] + assert args[0].agent == gcd_agent.Agent(parent='parent_value') + + +@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'), + ) + + +def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): + 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_from_dict(): + test_delete_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): + 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_from_dict(): + test_search_agents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) + for i in results) + +def test_search_agents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): + 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_from_dict(): + test_train_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): + 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_from_dict(): + test_export_agent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): + 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_from_dict(): + test_import_agent(request_type=dict) + + +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'] + + +def test_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): + 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_from_dict(): + test_restore_agent(request_type=dict) + + +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'] + + +def test_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): + 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_from_dict(): + test_get_validation_result(request_type=dict) + + +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'] + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_agents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_agents_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_agents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_agents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_agents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_agents_host_no_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_host_with_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..e09f748c2 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py @@ -0,0 +1,1814 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.answer_records.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.cloud.dialogflow_v2beta1.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_client_get_transport_class(): + transport = AnswerRecordsClient.get_transport_class() + available_transports = [ + transports.AnswerRecordsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_get_answer_record(transport: str = 'grpc', request_type=answer_record.GetAnswerRecordRequest): + 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_from_dict(): + test_get_answer_record(request_type=dict) + + +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'] + + +def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): + 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_from_dict(): + test_list_answer_records(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, answer_record.AnswerRecord) + for i in results) + +def test_list_answer_records_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_update_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + 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_from_dict(): + test_update_answer_record(request_type=dict) + + +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 = 'answer_record.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=answer_record.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 = 'answer_record.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=answer_record.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] + assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=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']), + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_answer_records_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_answer_records_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_answer_records_host_no_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_host_with_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..c958070d5 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py @@ -0,0 +1,2595 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.contexts import ContextsAsyncClient +from google.cloud.dialogflow_v2beta1.services.contexts import ContextsClient +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.services.contexts import transports +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_client_get_transport_class(): + transport = ContextsClient.get_transport_class() + available_transports = [ + transports.ContextsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): + 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_from_dict(): + test_list_contexts(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, context.Context) + for i in results) + +def test_list_contexts_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): + 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_from_dict(): + test_get_context(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): + 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_from_dict(): + test_create_context(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].context == gcd_context.Context(name='name_value') + + +def test_create_context_flattened_error(): + client = ContextsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].context == gcd_context.Context(name='name_value') + + +@pytest.mark.asyncio +async def test_create_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=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'), + ) + + +def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): + 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_from_dict(): + test_update_context(request_type=dict) + + +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 = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=context.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 = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + 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=context.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] + assert args[0].context == gcd_context.Context(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].context == gcd_context.Context(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=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']), + ) + + +def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): + 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_from_dict(): + test_delete_context(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): + 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_from_dict(): + test_delete_all_contexts(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_contexts_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_contexts_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_contexts_host_no_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_host_with_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..a2807e988 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py @@ -0,0 +1,2459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.conversation_profiles.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.cloud.dialogflow_v2beta1.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_client_get_transport_class(): + transport = ConversationProfilesClient.get_transport_class() + available_transports = [ + transports.ConversationProfilesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): + 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_from_dict(): + test_list_conversation_profiles(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation_profile.ConversationProfile) + for i in results) + +def test_list_conversation_profiles_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): + 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', + ) + 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' + + +def test_get_conversation_profile_from_dict(): + test_get_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + 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', + ) + 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' + + +def test_create_conversation_profile_from_dict(): + test_create_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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] + assert args[0].parent == 'parent_value' + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + + +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] + assert args[0].parent == 'parent_value' + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + + +@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'), + ) + + +def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + 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', + ) + 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' + + +def test_update_conversation_profile_from_dict(): + test_update_conversation_profile(request_type=dict) + + +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', + )) + 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' + + +@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 = 'conversation_profile.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=conversation_profile.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 = 'conversation_profile.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=conversation_profile.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] + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=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']), + ) + + +def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): + 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_from_dict(): + test_delete_conversation_profile(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_conversation_profiles_host_no_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_host_with_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_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 = ConversationProfilesClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", + } + 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 = "cuttlefish" + knowledge_base = "mussel" + 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": "winkle", + "knowledge_base": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationProfilesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationProfilesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = ConversationProfilesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..dfc4b944b --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py @@ -0,0 +1,2848 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.conversations.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import session +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_client_get_transport_class(): + transport = ConversationsClient.get_transport_class() + available_transports = [ + transports.ConversationsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): + 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_from_dict(): + test_create_conversation(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].conversation == gcd_conversation.Conversation(name='name_value') + + +def test_create_conversation_flattened_error(): + client = ConversationsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].conversation == gcd_conversation.Conversation(name='name_value') + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=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'), + ) + + +def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): + 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_from_dict(): + test_list_conversations(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + +def test_list_conversations_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): + 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_from_dict(): + test_get_conversation(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): + 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_from_dict(): + test_complete_conversation(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_batch_create_messages(transport: str = 'grpc', request_type=conversation.BatchCreateMessagesRequest): + 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_from_dict(): + test_batch_create_messages(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): + 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_from_dict(): + test_list_messages(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Message) + for i in results) + +def test_list_messages_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_conversations_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_conversations_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_conversations_host_no_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_host_with_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_conversation_path(): + project = "squid" + conversation = "clam" + 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": "whelk", + "conversation": "octopus", + } + 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 = "oyster" + conversation_profile = "nudibranch" + 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": "cuttlefish", + "conversation_profile": "mussel", + } + 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 = "winkle" + conversation = "nautilus" + message = "scallop" + 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": "abalone", + "conversation": "squid", + "message": "clam", + } + 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 = "whelk" + 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": "octopus", + } + 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 = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + 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 = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + 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 = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConversationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + 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 = "scallop" + location = "abalone" + 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": "squid", + "location": "clam", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..89df61b8b --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py @@ -0,0 +1,2804 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.documents import DocumentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.documents import DocumentsClient +from google.cloud.dialogflow_v2beta1.services.documents import pagers +from google.cloud.dialogflow_v2beta1.services.documents import transports +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.cloud.dialogflow_v2beta1.types import gcs +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_client_get_transport_class(): + transport = DocumentsClient.get_transport_class() + available_transports = [ + transports.DocumentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): + 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_from_dict(): + test_list_documents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + +def test_list_documents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): + 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, + 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 + + +def test_get_document_from_dict(): + test_get_document(request_type=dict) + + +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, + )) + 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 + + +@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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): + 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_from_dict(): + test_create_document(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].document == gcd_document.Document(name='name_value') + + +def test_create_document_flattened_error(): + client = DocumentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].document == gcd_document.Document(name='name_value') + + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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'), + ) + + +def test_import_documents(transport: str = 'grpc', request_type=document.ImportDocumentsRequest): + 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_from_dict(): + test_import_documents(request_type=dict) + + +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'] + + +def test_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): + 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_from_dict(): + test_delete_document(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): + 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_from_dict(): + test_update_document(request_type=dict) + + +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 = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=document.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 = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = 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=document.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] + assert args[0].document == gcd_document.Document(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].document == gcd_document.Document(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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']), + ) + + +def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): + 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_from_dict(): + test_reload_document(request_type=dict) + + +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] + assert args[0].name == 'name_value' + assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') + + +def test_reload_document_flattened_error(): + client = DocumentsClient( + credentials=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] + assert args[0].name == 'name_value' + assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') + + +@pytest.mark.asyncio +async def test_reload_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=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'), + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_documents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_documents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_documents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_documents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_documents_host_no_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_host_with_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..ea5e97a3e --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py @@ -0,0 +1,3580 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesClient +from google.cloud.dialogflow_v2beta1.services.entity_types import pagers +from google.cloud.dialogflow_v2beta1.services.entity_types import transports +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_client_get_transport_class(): + transport = EntityTypesClient.get_transport_class() + available_transports = [ + transports.EntityTypesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): + 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_from_dict(): + test_list_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, entity_type.EntityType) + for i in results) + +def test_list_entity_types_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): + 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_from_dict(): + test_get_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): + 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_from_dict(): + test_create_entity_type(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +def test_create_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): + 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_from_dict(): + test_update_entity_type(request_type=dict) + + +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 = 'entity_type.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=entity_type.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 = 'entity_type.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=entity_type.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] + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') + assert args[0].language_code == 'language_code_value' + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@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']), + ) + + +def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): + 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_from_dict(): + test_delete_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): + 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_from_dict(): + test_batch_update_entity_types(request_type=dict) + + +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'] + + +def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): + 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_from_dict(): + test_batch_delete_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type_names == ['entity_type_names_value'] + + +def test_batch_delete_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_type_names == ['entity_type_names_value'] + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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'], + ) + + +def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): + 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_from_dict(): + test_batch_create_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +def test_batch_create_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): + 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_from_dict(): + test_batch_update_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +def test_batch_update_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): + 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_from_dict(): + test_batch_delete_entities(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].entity_values == ['entity_values_value'] + assert args[0].language_code == 'language_code_value' + + +def test_batch_delete_entities_flattened_error(): + client = EntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].entity_values == ['entity_values_value'] + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_entity_types_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_entity_types_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_entity_types_host_no_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_host_with_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..b7098b932 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py @@ -0,0 +1,2420 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.environments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.environments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): + 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_from_dict(): + test_list_environments(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(): + client = EnvironmentsClient( + credentials=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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.Environment) + for i in results) + +def test_list_environments_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): + 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_from_dict(): + test_get_environment(request_type=dict) + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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'] + + +def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + )) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_get_environment_history_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in results) + +def test_get_environment_history_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_environments', + 'get_environment', + 'create_environment', + 'update_environment', + 'delete_environment', + 'get_environment_history', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_environments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_environments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_environments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_environments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + 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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..974401ebc --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py @@ -0,0 +1,1487 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import transports +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +def test_fulfillments_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FulfillmentsGrpcTransport, + ) + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_fulfillment', + 'update_fulfillment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_fulfillments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_fulfillments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_fulfillments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/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 new file mode 100644 index 000000000..4ce1b74ae --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py @@ -0,0 +1,3100 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.intents import IntentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.intents import IntentsClient +from google.cloud.dialogflow_v2beta1.services.intents import pagers +from google.cloud.dialogflow_v2beta1.services.intents import transports +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_client_get_transport_class(): + transport = IntentsClient.get_transport_class() + available_transports = [ + transports.IntentsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): + 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_from_dict(): + test_list_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].parent == 'parent_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_list_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, intent.Intent) + for i in results) + +def test_list_intents_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): + 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_from_dict(): + test_get_intent(request_type=dict) + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +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] + assert args[0].name == 'name_value' + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): + 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_from_dict(): + test_create_intent(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + + +def test_create_intent_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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', + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): + 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_from_dict(): + test_update_intent(request_type=dict) + + +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 = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=intent.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 = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + 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=intent.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] + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].language_code == 'language_code_value' + + +def test_update_intent_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].intent == gcd_intent.Intent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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', + ) + + +def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): + 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_from_dict(): + test_delete_intent(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): + 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_from_dict(): + test_batch_update_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +def test_batch_update_intents_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + 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')]), + ) + + +def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): + 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_from_dict(): + test_batch_delete_intents(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].intents == [intent.Intent(name='name_value')] + + +def test_batch_delete_intents_flattened_error(): + client = IntentsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].intents == [intent.Intent(name='name_value')] + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=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')], + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_intents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_intents_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_intents_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_intents_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_intents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_intents_host_no_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_host_with_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..114d5265f --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py @@ -0,0 +1,2378 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.knowledge_bases.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_client_get_transport_class(): + transport = KnowledgeBasesClient.get_transport_class() + available_transports = [ + transports.KnowledgeBasesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): + 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_from_dict(): + test_list_knowledge_bases(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, knowledge_base.KnowledgeBase) + for i in results) + +def test_list_knowledge_bases_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): + 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_from_dict(): + test_get_knowledge_base(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + 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_from_dict(): + test_create_knowledge_base(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + + +def test_create_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + + +@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'), + ) + + +def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + 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_from_dict(): + test_delete_knowledge_base(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + 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_from_dict(): + test_update_knowledge_base(request_type=dict) + + +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 = 'knowledge_base.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=knowledge_base.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 = 'knowledge_base.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=knowledge_base.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] + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=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']), + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_knowledge_bases_host_no_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_host_with_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..99ad36723 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py @@ -0,0 +1,3710 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.participants.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.participants.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import context +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.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_client_get_transport_class(): + transport = ParticipantsClient.get_transport_class() + available_transports = [ + transports.ParticipantsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): + 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_from_dict(): + test_create_participant(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].participant == gcd_participant.Participant(name='name_value') + + +def test_create_participant_flattened_error(): + client = ParticipantsClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].participant == gcd_participant.Participant(name='name_value') + + +@pytest.mark.asyncio +async def test_create_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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'), + ) + + +def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): + 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_from_dict(): + test_get_participant(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): + 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_from_dict(): + test_list_participants(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Participant) + for i in results) + +def test_list_participants_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_update_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): + 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_from_dict(): + test_update_participant(request_type=dict) + + +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 = 'participant.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=participant.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 = 'participant.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=participant.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] + assert args[0].participant == gcd_participant.Participant(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].participant == gcd_participant.Participant(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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']), + ) + + +def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): + 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_from_dict(): + test_analyze_content(request_type=dict) + + +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] + assert args[0].participant == 'participant_value' + assert args[0].event_input == session.EventInput(name='name_value') + + +def test_analyze_content_flattened_error(): + client = ParticipantsClient( + credentials=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] + assert args[0].participant == 'participant_value' + assert args[0].event_input == session.EventInput(name='name_value') + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=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'), + ) + + +def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): + 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_from_dict(): + test_suggest_articles(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): + 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_from_dict(): + test_suggest_faq_answers(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_suggest_smart_replies(transport: str = 'grpc', request_type=participant.SuggestSmartRepliesRequest): + 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_from_dict(): + test_suggest_smart_replies(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_list_suggestions(transport: str = 'grpc', request_type=participant.ListSuggestionsRequest): + 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_from_dict(): + test_list_suggestions(request_type=dict) + + +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(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Suggestion) + for i in results) + +def test_list_suggestions_pages(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_compile_suggestion(transport: str = 'grpc', request_type=participant.CompileSuggestionRequest): + 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_from_dict(): + test_compile_suggestion(request_type=dict) + + +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'] + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + 'suggest_articles', + 'suggest_faq_answers', + 'suggest_smart_replies', + 'list_suggestions', + 'compile_suggestion', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_participants_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_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() + + +@requires_google_auth_gte_1_25_0 +def test_participants_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_participants_host_no_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_host_with_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_context_path(): + project = "squid" + session = "clam" + context = "whelk" + 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": "octopus", + "session": "oyster", + "context": "nudibranch", + } + 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 = "cuttlefish" + knowledge_base = "mussel" + document = "winkle" + 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": "nautilus", + "knowledge_base": "scallop", + "document": "abalone", + } + 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 = "squid" + intent = "clam" + 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": "whelk", + "intent": "octopus", + } + 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 = "oyster" + conversation = "nudibranch" + message = "cuttlefish" + 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": "mussel", + "conversation": "winkle", + "message": "nautilus", + } + 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 = "scallop" + conversation = "abalone" + participant = "squid" + 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": "clam", + "conversation": "whelk", + "participant": "octopus", + } + 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 = "oyster" + session = "nudibranch" + entity_type = "cuttlefish" + 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": "mussel", + "session": "winkle", + "entity_type": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = ParticipantsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ParticipantsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = ParticipantsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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_withDEFAULT_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) 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 new file mode 100644 index 000000000..04a57bd5e --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py @@ -0,0 +1,2369 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.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.services.session_entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_client_get_transport_class(): + transport = SessionEntityTypesClient.get_transport_class() + available_transports = [ + transports.SessionEntityTypesGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): + 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_from_dict(): + test_list_session_entity_types(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, session_entity_type.SessionEntityType) + for i in results) + +def test_list_session_entity_types_pages(): + 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: + # 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: + 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: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): + 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_from_dict(): + test_get_session_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + 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_from_dict(): + test_create_session_entity_type(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + + +def test_create_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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] + assert args[0].parent == 'parent_value' + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + + +@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'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + 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_from_dict(): + test_update_session_entity_type(request_type=dict) + + +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 = 'session_entity_type.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=session_entity_type.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 = 'session_entity_type.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=session_entity_type.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] + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +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] + assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=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']), + ) + + +def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + 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_from_dict(): + test_delete_session_entity_type(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_session_entity_types_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=( '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, + ], +) +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_session_entity_types_host_no_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_host_with_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..835506f4a --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py @@ -0,0 +1,1403 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.sessions import SessionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.sessions import SessionsClient +from google.cloud.dialogflow_v2beta1.services.sessions import transports +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import context +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.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 + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_client_get_transport_class(): + transport = SessionsClient.get_transport_class() + available_transports = [ + transports.SessionsGrpcTransport, + ] + 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"), +]) +@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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_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, + ) + + +def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): + 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_from_dict(): + test_detect_intent(request_type=dict) + + +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] + assert args[0].session == 'session_value' + assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + + +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] + assert args[0].session == 'session_value' + assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + + +@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)), + ) + + +def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): + 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) + + +def test_streaming_detect_intent_from_dict(): + test_streaming_detect_intent(request_type=dict) + + +@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) + + +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 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, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_sessions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_sessions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() + + +@requires_google_auth_gte_1_25_0 +def test_sessions_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_sessions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_sessions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_sessions_host_no_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_host_with_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_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_withDEFAULT_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) 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 new file mode 100644 index 000000000..e3fb07f88 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py @@ -0,0 +1,2391 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.versions import VersionsClient +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.services.versions import transports +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +def test_versions_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +def test_list_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = version.ListVersionsResponse() + client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_versions_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_versions_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_versions_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +def test_list_versions_pager(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) + for i in results) + +def test_list_versions_pages(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = list(client.list_versions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_versions_async_pager(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_versions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, version.Version) + for i in responses) + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +def test_get_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = version.Version() + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_version( + version.GetVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_version( + version.GetVersionRequest(), + name='name_value', + ) + + +def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +def test_create_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].version == gcd_version.Version(name='name_value') + + +def test_create_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].version == gcd_version.Version(name='name_value') + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +def test_update_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +def test_update_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +def test_delete_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = None + client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_version_flattened_error(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VersionsGrpcTransport, + ) + +def test_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_versions', + 'get_version', + 'create_version', + 'update_version', + 'delete_version', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_versions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_versions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_versions_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_versions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_versions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 0543d58d43e3eb587e851bfeb193077a19703a48 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 14 May 2021 05:06:17 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/dialogflow_v2/agents.rst | 1 - docs/dialogflow_v2/answer_records.rst | 1 - docs/dialogflow_v2/contexts.rst | 1 - docs/dialogflow_v2/conversation_profiles.rst | 1 - docs/dialogflow_v2/conversations.rst | 1 - docs/dialogflow_v2/documents.rst | 1 - docs/dialogflow_v2/entity_types.rst | 1 - docs/dialogflow_v2/environments.rst | 1 - .../dialogflow_v2/fulfillments.rst | 0 docs/dialogflow_v2/intents.rst | 1 - docs/dialogflow_v2/knowledge_bases.rst | 1 - docs/dialogflow_v2/participants.rst | 1 - docs/dialogflow_v2/services.rst | 2 + docs/dialogflow_v2/session_entity_types.rst | 1 - .../docs => docs}/dialogflow_v2/versions.rst | 0 docs/dialogflow_v2beta1/agents.rst | 1 - docs/dialogflow_v2beta1/answer_records.rst | 1 - docs/dialogflow_v2beta1/contexts.rst | 1 - .../conversation_profiles.rst | 1 - docs/dialogflow_v2beta1/conversations.rst | 1 - docs/dialogflow_v2beta1/documents.rst | 1 - docs/dialogflow_v2beta1/entity_types.rst | 1 - docs/dialogflow_v2beta1/environments.rst | 1 - .../dialogflow_v2beta1/fulfillments.rst | 0 docs/dialogflow_v2beta1/intents.rst | 1 - docs/dialogflow_v2beta1/knowledge_bases.rst | 1 - docs/dialogflow_v2beta1/participants.rst | 1 - docs/dialogflow_v2beta1/services.rst | 2 + .../session_entity_types.rst | 1 - .../dialogflow_v2beta1/versions.rst | 0 google/cloud/dialogflow/__init__.py | 358 +- google/cloud/dialogflow_v2/__init__.py | 83 +- .../cloud/dialogflow_v2/gapic_metadata.json | 0 .../cloud/dialogflow_v2/services/__init__.py | 1 - .../dialogflow_v2/services/agents/__init__.py | 2 - .../services/agents/async_client.py | 60 +- .../dialogflow_v2/services/agents/client.py | 103 +- .../dialogflow_v2/services/agents/pagers.py | 4 +- .../services/agents/transports/__init__.py | 2 - .../services/agents/transports/base.py | 145 +- .../services/agents/transports/grpc.py | 48 +- .../agents/transports/grpc_asyncio.py | 47 +- .../services/answer_records/__init__.py | 2 - .../services/answer_records/async_client.py | 43 +- .../services/answer_records/client.py | 82 +- .../services/answer_records/pagers.py | 4 +- .../answer_records/transports/__init__.py | 2 - .../answer_records/transports/base.py | 111 +- .../answer_records/transports/grpc.py | 22 +- .../answer_records/transports/grpc_asyncio.py | 23 +- .../services/contexts/__init__.py | 2 - .../services/contexts/async_client.py | 42 +- .../dialogflow_v2/services/contexts/client.py | 85 +- .../dialogflow_v2/services/contexts/pagers.py | 4 +- .../services/contexts/transports/__init__.py | 2 - .../services/contexts/transports/base.py | 127 +- .../services/contexts/transports/grpc.py | 34 +- .../contexts/transports/grpc_asyncio.py | 33 +- .../conversation_profiles/__init__.py | 2 - .../conversation_profiles/async_client.py | 46 +- .../services/conversation_profiles/client.py | 112 +- .../services/conversation_profiles/pagers.py | 4 +- .../transports/__init__.py | 2 - .../conversation_profiles/transports/base.py | 128 +- .../conversation_profiles/transports/grpc.py | 30 +- .../transports/grpc_asyncio.py | 30 +- .../services/conversations/__init__.py | 2 - .../services/conversations/async_client.py | 36 +- .../services/conversations/client.py | 86 +- .../services/conversations/pagers.py | 6 +- .../conversations/transports/__init__.py | 2 - .../services/conversations/transports/base.py | 129 +- .../services/conversations/transports/grpc.py | 22 +- .../conversations/transports/grpc_asyncio.py | 23 +- .../services/documents/__init__.py | 2 - .../services/documents/async_client.py | 44 +- .../services/documents/client.py | 87 +- .../services/documents/pagers.py | 4 +- .../services/documents/transports/__init__.py | 2 - .../services/documents/transports/base.py | 127 +- .../services/documents/transports/grpc.py | 40 +- .../documents/transports/grpc_asyncio.py | 45 +- .../services/entity_types/__init__.py | 2 - .../services/entity_types/async_client.py | 70 +- .../services/entity_types/client.py | 112 +- .../services/entity_types/pagers.py | 4 +- .../entity_types/transports/__init__.py | 2 - .../services/entity_types/transports/base.py | 148 +- .../services/entity_types/transports/grpc.py | 54 +- .../entity_types/transports/grpc_asyncio.py | 51 +- .../services/environments/__init__.py | 2 - .../services/environments/async_client.py | 369 +- .../services/environments/client.py | 419 +- .../services/environments/pagers.py | 132 +- .../environments/transports/__init__.py | 2 - .../services/environments/transports/base.py | 169 +- .../services/environments/transports/grpc.py | 167 +- .../environments/transports/grpc_asyncio.py | 175 +- .../services/fulfillments/__init__.py | 4 +- .../services/fulfillments/async_client.py | 128 +- .../services/fulfillments/client.py | 165 +- .../fulfillments/transports/__init__.py | 10 +- .../services/fulfillments/transports/base.py | 94 +- .../services/fulfillments/transports/grpc.py | 87 +- .../fulfillments/transports/grpc_asyncio.py | 91 +- .../services/intents/__init__.py | 2 - .../services/intents/async_client.py | 53 +- .../dialogflow_v2/services/intents/client.py | 100 +- .../dialogflow_v2/services/intents/pagers.py | 4 +- .../services/intents/transports/__init__.py | 2 - .../services/intents/transports/base.py | 134 +- .../services/intents/transports/grpc.py | 38 +- .../intents/transports/grpc_asyncio.py | 43 +- .../services/knowledge_bases/__init__.py | 2 - .../services/knowledge_bases/async_client.py | 38 +- .../services/knowledge_bases/client.py | 80 +- .../services/knowledge_bases/pagers.py | 4 +- .../knowledge_bases/transports/__init__.py | 2 - .../knowledge_bases/transports/base.py | 128 +- .../knowledge_bases/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 31 +- .../services/participants/__init__.py | 2 - .../services/participants/async_client.py | 46 +- .../services/participants/client.py | 102 +- .../services/participants/pagers.py | 4 +- .../participants/transports/__init__.py | 2 - .../services/participants/transports/base.py | 144 +- .../services/participants/transports/grpc.py | 22 +- .../participants/transports/grpc_asyncio.py | 23 +- .../services/session_entity_types/__init__.py | 2 - .../session_entity_types/async_client.py | 38 +- .../services/session_entity_types/client.py | 80 +- .../services/session_entity_types/pagers.py | 4 +- .../transports/__init__.py | 2 - .../session_entity_types/transports/base.py | 128 +- .../session_entity_types/transports/grpc.py | 30 +- .../transports/grpc_asyncio.py | 29 +- .../services/sessions/__init__.py | 2 - .../services/sessions/async_client.py | 32 +- .../dialogflow_v2/services/sessions/client.py | 78 +- .../services/sessions/transports/__init__.py | 2 - .../services/sessions/transports/base.py | 114 +- .../services/sessions/transports/grpc.py | 22 +- .../sessions/transports/grpc_asyncio.py | 23 +- .../services/versions/__init__.py | 4 +- .../services/versions/async_client.py | 227 +- .../dialogflow_v2/services/versions/client.py | 280 +- .../dialogflow_v2/services/versions/pagers.py | 45 +- .../services/versions/transports/__init__.py | 10 +- .../services/versions/transports/base.py | 141 +- .../services/versions/transports/grpc.py | 125 +- .../versions/transports/grpc_asyncio.py | 130 +- google/cloud/dialogflow_v2/types/__init__.py | 40 +- google/cloud/dialogflow_v2/types/agent.py | 87 +- .../dialogflow_v2/types/answer_record.py | 50 +- .../cloud/dialogflow_v2/types/audio_config.py | 66 +- google/cloud/dialogflow_v2/types/context.py | 40 +- .../cloud/dialogflow_v2/types/conversation.py | 59 +- .../dialogflow_v2/types/conversation_event.py | 12 +- .../types/conversation_profile.py | 146 +- google/cloud/dialogflow_v2/types/document.py | 65 +- .../cloud/dialogflow_v2/types/entity_type.py | 101 +- .../cloud/dialogflow_v2/types/environment.py | 259 +- .../cloud/dialogflow_v2/types/fulfillment.py | 82 +- google/cloud/dialogflow_v2/types/gcs.py | 1 - .../types/human_agent_assistant_event.py | 9 +- google/cloud/dialogflow_v2/types/intent.py | 319 +- .../dialogflow_v2/types/knowledge_base.py | 39 +- .../cloud/dialogflow_v2/types/participant.py | 158 +- google/cloud/dialogflow_v2/types/session.py | 154 +- .../types/session_entity_type.py | 32 +- .../dialogflow_v2/types/validation_result.py | 10 +- .../cloud/dialogflow_v2/types/version.py | 101 +- google/cloud/dialogflow_v2/types/webhook.py | 33 +- google/cloud/dialogflow_v2beta1/__init__.py | 91 +- .../dialogflow_v2beta1/gapic_metadata.json | 0 .../dialogflow_v2beta1/services/__init__.py | 1 - .../services/agents/__init__.py | 2 - .../services/agents/async_client.py | 60 +- .../services/agents/client.py | 103 +- .../services/agents/pagers.py | 4 +- .../services/agents/transports/__init__.py | 2 - .../services/agents/transports/base.py | 145 +- .../services/agents/transports/grpc.py | 48 +- .../agents/transports/grpc_asyncio.py | 47 +- .../services/answer_records/__init__.py | 2 - .../services/answer_records/async_client.py | 54 +- .../services/answer_records/client.py | 93 +- .../services/answer_records/pagers.py | 4 +- .../answer_records/transports/__init__.py | 2 - .../answer_records/transports/base.py | 117 +- .../answer_records/transports/grpc.py | 22 +- .../answer_records/transports/grpc_asyncio.py | 23 +- .../services/contexts/__init__.py | 2 - .../services/contexts/async_client.py | 42 +- .../services/contexts/client.py | 85 +- .../services/contexts/pagers.py | 4 +- .../services/contexts/transports/__init__.py | 2 - .../services/contexts/transports/base.py | 127 +- .../services/contexts/transports/grpc.py | 34 +- .../contexts/transports/grpc_asyncio.py | 33 +- .../conversation_profiles/__init__.py | 2 - .../conversation_profiles/async_client.py | 46 +- .../services/conversation_profiles/client.py | 112 +- .../services/conversation_profiles/pagers.py | 4 +- .../transports/__init__.py | 2 - .../conversation_profiles/transports/base.py | 128 +- .../conversation_profiles/transports/grpc.py | 30 +- .../transports/grpc_asyncio.py | 30 +- .../services/conversations/__init__.py | 2 - .../services/conversations/async_client.py | 42 +- .../services/conversations/client.py | 93 +- .../services/conversations/pagers.py | 6 +- .../conversations/transports/__init__.py | 2 - .../services/conversations/transports/base.py | 135 +- .../services/conversations/transports/grpc.py | 22 +- .../conversations/transports/grpc_asyncio.py | 23 +- .../services/documents/__init__.py | 2 - .../services/documents/async_client.py | 50 +- .../services/documents/client.py | 93 +- .../services/documents/pagers.py | 4 +- .../services/documents/transports/__init__.py | 2 - .../services/documents/transports/base.py | 131 +- .../services/documents/transports/grpc.py | 48 +- .../documents/transports/grpc_asyncio.py | 55 +- .../services/entity_types/__init__.py | 2 - .../services/entity_types/async_client.py | 74 +- .../services/entity_types/client.py | 116 +- .../services/entity_types/pagers.py | 4 +- .../entity_types/transports/__init__.py | 2 - .../services/entity_types/transports/base.py | 148 +- .../services/entity_types/transports/grpc.py | 54 +- .../entity_types/transports/grpc_asyncio.py | 51 +- .../services/environments/__init__.py | 2 - .../services/environments/async_client.py | 348 +- .../services/environments/client.py | 400 +- .../services/environments/pagers.py | 132 +- .../environments/transports/__init__.py | 2 - .../services/environments/transports/base.py | 169 +- .../services/environments/transports/grpc.py | 167 +- .../environments/transports/grpc_asyncio.py | 175 +- .../services/fulfillments/__init__.py | 4 +- .../services/fulfillments/async_client.py | 128 +- .../services/fulfillments/client.py | 165 +- .../fulfillments/transports/__init__.py | 10 +- .../services/fulfillments/transports/base.py | 94 +- .../services/fulfillments/transports/grpc.py | 87 +- .../fulfillments/transports/grpc_asyncio.py | 91 +- .../services/intents/__init__.py | 2 - .../services/intents/async_client.py | 53 +- .../services/intents/client.py | 100 +- .../services/intents/pagers.py | 4 +- .../services/intents/transports/__init__.py | 2 - .../services/intents/transports/base.py | 134 +- .../services/intents/transports/grpc.py | 38 +- .../intents/transports/grpc_asyncio.py | 43 +- .../services/knowledge_bases/__init__.py | 2 - .../services/knowledge_bases/async_client.py | 38 +- .../services/knowledge_bases/client.py | 80 +- .../services/knowledge_bases/pagers.py | 4 +- .../knowledge_bases/transports/__init__.py | 2 - .../knowledge_bases/transports/base.py | 128 +- .../knowledge_bases/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 31 +- .../services/participants/__init__.py | 2 - .../services/participants/async_client.py | 58 +- .../services/participants/client.py | 119 +- .../services/participants/pagers.py | 6 +- .../participants/transports/__init__.py | 2 - .../services/participants/transports/base.py | 162 +- .../services/participants/transports/grpc.py | 28 +- .../participants/transports/grpc_asyncio.py | 29 +- .../services/session_entity_types/__init__.py | 2 - .../session_entity_types/async_client.py | 38 +- .../services/session_entity_types/client.py | 80 +- .../services/session_entity_types/pagers.py | 4 +- .../transports/__init__.py | 2 - .../session_entity_types/transports/base.py | 128 +- .../session_entity_types/transports/grpc.py | 30 +- .../transports/grpc_asyncio.py | 29 +- .../services/sessions/__init__.py | 2 - .../services/sessions/async_client.py | 32 +- .../services/sessions/client.py | 82 +- .../services/sessions/transports/__init__.py | 2 - .../services/sessions/transports/base.py | 114 +- .../services/sessions/transports/grpc.py | 22 +- .../sessions/transports/grpc_asyncio.py | 23 +- .../services/versions/__init__.py | 4 +- .../services/versions/async_client.py | 227 +- .../services/versions/client.py | 280 +- .../services/versions/pagers.py | 45 +- .../services/versions/transports/__init__.py | 10 +- .../services/versions/transports/base.py | 141 +- .../services/versions/transports/grpc.py | 125 +- .../versions/transports/grpc_asyncio.py | 130 +- .../dialogflow_v2beta1/types/__init__.py | 40 +- .../cloud/dialogflow_v2beta1/types/agent.py | 93 +- .../dialogflow_v2beta1/types/answer_record.py | 59 +- .../dialogflow_v2beta1/types/audio_config.py | 67 +- .../cloud/dialogflow_v2beta1/types/context.py | 40 +- .../dialogflow_v2beta1/types/conversation.py | 67 +- .../types/conversation_event.py | 12 +- .../types/conversation_profile.py | 142 +- .../dialogflow_v2beta1/types/document.py | 91 +- .../dialogflow_v2beta1/types/entity_type.py | 101 +- .../dialogflow_v2beta1/types/environment.py | 242 +- .../dialogflow_v2beta1/types/fulfillment.py | 82 +- google/cloud/dialogflow_v2beta1/types/gcs.py | 8 +- .../types/human_agent_assistant_event.py | 9 +- .../cloud/dialogflow_v2beta1/types/intent.py | 380 +- .../types/knowledge_base.py | 42 +- .../dialogflow_v2beta1/types/participant.py | 285 +- .../cloud/dialogflow_v2beta1/types/session.py | 180 +- .../types/session_entity_type.py | 32 +- .../types/validation_result.py | 10 +- .../cloud/dialogflow_v2beta1/types/version.py | 101 +- .../cloud/dialogflow_v2beta1/types/webhook.py | 40 +- 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_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/intents.rst | 10 - .../v2/docs/dialogflow_v2/knowledge_bases.rst | 10 - .../v2/docs/dialogflow_v2/participants.rst | 10 - .../v2/docs/dialogflow_v2/services.rst | 20 - .../dialogflow_v2/session_entity_types.rst | 10 - .../v2/docs/dialogflow_v2/sessions.rst | 6 - .../v2/docs/dialogflow_v2/types.rst | 7 - owl-bot-staging/v2/docs/index.rst | 7 - .../v2/google/cloud/dialogflow/__init__.py | 419 -- .../v2/google/cloud/dialogflow/py.typed | 2 - .../v2/google/cloud/dialogflow_v2/__init__.py | 420 -- .../v2/google/cloud/dialogflow_v2/py.typed | 2 - .../dialogflow_v2/services/agents/__init__.py | 22 - .../services/agents/async_client.py | 922 ---- .../dialogflow_v2/services/agents/client.py | 1112 ----- .../dialogflow_v2/services/agents/pagers.py | 140 - .../services/agents/transports/__init__.py | 33 - .../services/agents/transports/base.py | 305 -- .../services/agents/transports/grpc.py | 522 --- .../agents/transports/grpc_asyncio.py | 526 --- .../services/answer_records/__init__.py | 22 - .../services/answer_records/async_client.py | 370 -- .../services/answer_records/client.py | 557 --- .../services/answer_records/pagers.py | 140 - .../answer_records/transports/__init__.py | 33 - .../answer_records/transports/base.py | 198 - .../answer_records/transports/grpc.py | 277 -- .../answer_records/transports/grpc_asyncio.py | 281 -- .../services/contexts/__init__.py | 22 - .../services/contexts/async_client.py | 703 ---- .../dialogflow_v2/services/contexts/client.py | 890 ---- .../dialogflow_v2/services/contexts/pagers.py | 140 - .../services/contexts/transports/__init__.py | 33 - .../services/contexts/transports/base.py | 255 -- .../services/contexts/transports/grpc.py | 383 -- .../contexts/transports/grpc_asyncio.py | 387 -- .../conversation_profiles/__init__.py | 22 - .../conversation_profiles/async_client.py | 594 --- .../services/conversation_profiles/client.py | 817 ---- .../services/conversation_profiles/pagers.py | 140 - .../transports/__init__.py | 33 - .../conversation_profiles/transports/base.py | 241 -- .../conversation_profiles/transports/grpc.py | 368 -- .../transports/grpc_asyncio.py | 372 -- .../services/conversations/__init__.py | 22 - .../services/conversations/async_client.py | 625 --- .../services/conversations/client.py | 830 ---- .../services/conversations/pagers.py | 263 -- .../conversations/transports/__init__.py | 33 - .../services/conversations/transports/base.py | 240 -- .../services/conversations/transports/grpc.py | 381 -- .../conversations/transports/grpc_asyncio.py | 385 -- .../services/documents/__init__.py | 22 - .../services/documents/async_client.py | 773 ---- .../services/documents/client.py | 960 ----- .../services/documents/pagers.py | 140 - .../services/documents/transports/__init__.py | 33 - .../services/documents/transports/base.py | 261 -- .../services/documents/transports/grpc.py | 423 -- .../documents/transports/grpc_asyncio.py | 427 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 1195 ------ .../services/entity_types/client.py | 1383 ------ .../services/entity_types/pagers.py | 140 - .../entity_types/transports/__init__.py | 33 - .../services/entity_types/transports/base.py | 318 -- .../services/entity_types/transports/grpc.py | 522 --- .../entity_types/transports/grpc_asyncio.py | 526 --- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 607 --- .../services/environments/client.py | 808 ---- .../services/environments/pagers.py | 262 -- .../environments/transports/__init__.py | 33 - .../services/environments/transports/base.py | 254 -- .../services/environments/transports/grpc.py | 393 -- .../environments/transports/grpc_asyncio.py | 397 -- .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 871 ---- .../dialogflow_v2/services/intents/client.py | 1067 ----- .../dialogflow_v2/services/intents/pagers.py | 140 - .../services/intents/transports/__init__.py | 33 - .../services/intents/transports/base.py | 276 -- .../services/intents/transports/grpc.py | 433 -- .../intents/transports/grpc_asyncio.py | 437 -- .../services/knowledge_bases/__init__.py | 22 - .../services/knowledge_bases/async_client.py | 601 --- .../services/knowledge_bases/client.py | 788 ---- .../services/knowledge_bases/pagers.py | 140 - .../knowledge_bases/transports/__init__.py | 33 - .../knowledge_bases/transports/base.py | 241 -- .../knowledge_bases/transports/grpc.py | 356 -- .../transports/grpc_asyncio.py | 360 -- .../services/participants/__init__.py | 22 - .../services/participants/async_client.py | 766 ---- .../services/participants/client.py | 983 ----- .../services/participants/pagers.py | 140 - .../participants/transports/__init__.py | 33 - .../services/participants/transports/base.py | 274 -- .../services/participants/transports/grpc.py | 414 -- .../participants/transports/grpc_asyncio.py | 418 -- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 629 --- .../services/session_entity_types/client.py | 816 ---- .../services/session_entity_types/pagers.py | 140 - .../transports/__init__.py | 33 - .../session_entity_types/transports/base.py | 241 -- .../session_entity_types/transports/grpc.py | 374 -- .../transports/grpc_asyncio.py | 378 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 396 -- .../dialogflow_v2/services/sessions/client.py | 600 --- .../services/sessions/transports/__init__.py | 33 - .../services/sessions/transports/base.py | 204 - .../services/sessions/transports/grpc.py | 292 -- .../sessions/transports/grpc_asyncio.py | 296 -- .../cloud/dialogflow_v2/types/__init__.py | 398 -- .../google/cloud/dialogflow_v2/types/agent.py | 459 -- .../dialogflow_v2/types/answer_record.py | 350 -- .../cloud/dialogflow_v2/types/audio_config.py | 463 -- .../cloud/dialogflow_v2/types/context.py | 298 -- .../cloud/dialogflow_v2/types/conversation.py | 390 -- .../dialogflow_v2/types/conversation_event.py | 79 - .../types/conversation_profile.py | 834 ---- .../cloud/dialogflow_v2/types/document.py | 372 -- .../cloud/dialogflow_v2/types/entity_type.py | 561 --- .../cloud/dialogflow_v2/types/environment.py | 459 -- .../google/cloud/dialogflow_v2/types/gcs.py | 25 - .../types/human_agent_assistant_event.py | 61 - .../cloud/dialogflow_v2/types/intent.py | 1611 ------- .../dialogflow_v2/types/knowledge_base.py | 225 - .../cloud/dialogflow_v2/types/participant.py | 836 ---- .../cloud/dialogflow_v2/types/session.py | 964 ----- .../types/session_entity_type.py | 251 -- .../dialogflow_v2/types/validation_result.py | 93 - .../cloud/dialogflow_v2/types/webhook.py | 230 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 132 - .../scripts/fixup_dialogflow_v2_keywords.py | 257 -- owl-bot-staging/v2/setup.py | 53 - 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 | 3145 -------------- .../dialogflow_v2/test_answer_records.py | 1661 -------- .../unit/gapic/dialogflow_v2/test_contexts.py | 2595 ------------ .../test_conversation_profiles.py | 2458 ----------- .../gapic/dialogflow_v2/test_conversations.py | 2618 ------------ .../gapic/dialogflow_v2/test_documents.py | 2655 ------------ .../gapic/dialogflow_v2/test_entity_types.py | 3574 ---------------- .../gapic/dialogflow_v2/test_environments.py | 2420 ----------- .../unit/gapic/dialogflow_v2/test_intents.py | 3088 -------------- .../dialogflow_v2/test_knowledge_bases.py | 2378 ----------- .../gapic/dialogflow_v2/test_participants.py | 2957 ------------- .../test_session_entity_types.py | 2369 ----------- .../unit/gapic/dialogflow_v2/test_sessions.py | 1381 ------ 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/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 | 7 - owl-bot-staging/v2beta1/docs/index.rst | 7 - .../google/cloud/dialogflow/__init__.py | 463 -- .../v2beta1/google/cloud/dialogflow/py.typed | 2 - .../cloud/dialogflow_v2beta1/__init__.py | 464 --- .../google/cloud/dialogflow_v2beta1/py.typed | 2 - .../services/agents/__init__.py | 22 - .../services/agents/async_client.py | 930 ----- .../services/agents/client.py | 1120 ----- .../services/agents/pagers.py | 140 - .../services/agents/transports/__init__.py | 33 - .../services/agents/transports/base.py | 305 -- .../services/agents/transports/grpc.py | 524 --- .../agents/transports/grpc_asyncio.py | 528 --- .../services/answer_records/__init__.py | 22 - .../services/answer_records/async_client.py | 457 -- .../services/answer_records/client.py | 645 --- .../services/answer_records/pagers.py | 140 - .../answer_records/transports/__init__.py | 33 - .../answer_records/transports/base.py | 212 - .../answer_records/transports/grpc.py | 304 -- .../answer_records/transports/grpc_asyncio.py | 308 -- .../services/contexts/__init__.py | 22 - .../services/contexts/async_client.py | 731 ---- .../services/contexts/client.py | 918 ---- .../services/contexts/pagers.py | 140 - .../services/contexts/transports/__init__.py | 33 - .../services/contexts/transports/base.py | 255 -- .../services/contexts/transports/grpc.py | 384 -- .../contexts/transports/grpc_asyncio.py | 388 -- .../conversation_profiles/__init__.py | 22 - .../conversation_profiles/async_client.py | 594 --- .../services/conversation_profiles/client.py | 817 ---- .../services/conversation_profiles/pagers.py | 140 - .../transports/__init__.py | 33 - .../conversation_profiles/transports/base.py | 241 -- .../conversation_profiles/transports/grpc.py | 368 -- .../transports/grpc_asyncio.py | 372 -- .../services/conversations/__init__.py | 22 - .../services/conversations/async_client.py | 703 ---- .../services/conversations/client.py | 908 ---- .../services/conversations/pagers.py | 263 -- .../conversations/transports/__init__.py | 33 - .../services/conversations/transports/base.py | 254 -- .../services/conversations/transports/grpc.py | 409 -- .../conversations/transports/grpc_asyncio.py | 413 -- .../services/documents/__init__.py | 22 - .../services/documents/async_client.py | 845 ---- .../services/documents/client.py | 1033 ----- .../services/documents/pagers.py | 140 - .../services/documents/transports/__init__.py | 33 - .../services/documents/transports/base.py | 275 -- .../services/documents/transports/grpc.py | 454 -- .../documents/transports/grpc_asyncio.py | 458 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 1224 ------ .../services/entity_types/client.py | 1412 ------- .../services/entity_types/pagers.py | 140 - .../entity_types/transports/__init__.py | 33 - .../services/entity_types/transports/base.py | 318 -- .../services/entity_types/transports/grpc.py | 519 --- .../entity_types/transports/grpc_asyncio.py | 523 --- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 607 --- .../services/environments/client.py | 808 ---- .../services/environments/pagers.py | 262 -- .../environments/transports/__init__.py | 33 - .../services/environments/transports/base.py | 254 -- .../services/environments/transports/grpc.py | 393 -- .../environments/transports/grpc_asyncio.py | 397 -- .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 889 ---- .../services/intents/client.py | 1085 ----- .../services/intents/pagers.py | 140 - .../services/intents/transports/__init__.py | 33 - .../services/intents/transports/base.py | 276 -- .../services/intents/transports/grpc.py | 434 -- .../intents/transports/grpc_asyncio.py | 438 -- .../services/knowledge_bases/__init__.py | 22 - .../services/knowledge_bases/async_client.py | 615 --- .../services/knowledge_bases/client.py | 802 ---- .../services/knowledge_bases/pagers.py | 140 - .../knowledge_bases/transports/__init__.py | 33 - .../knowledge_bases/transports/base.py | 241 -- .../knowledge_bases/transports/grpc.py | 370 -- .../transports/grpc_asyncio.py | 374 -- .../services/participants/__init__.py | 22 - .../services/participants/async_client.py | 1007 ----- .../services/participants/client.py | 1235 ------ .../services/participants/pagers.py | 262 -- .../participants/transports/__init__.py | 33 - .../services/participants/transports/base.py | 316 -- .../services/participants/transports/grpc.py | 533 --- .../participants/transports/grpc_asyncio.py | 537 --- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 649 --- .../services/session_entity_types/client.py | 836 ---- .../services/session_entity_types/pagers.py | 140 - .../transports/__init__.py | 33 - .../session_entity_types/transports/base.py | 241 -- .../session_entity_types/transports/grpc.py | 374 -- .../transports/grpc_asyncio.py | 378 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 406 -- .../services/sessions/client.py | 619 --- .../services/sessions/transports/__init__.py | 33 - .../services/sessions/transports/base.py | 204 - .../services/sessions/transports/grpc.py | 292 -- .../sessions/transports/grpc_asyncio.py | 296 -- .../dialogflow_v2beta1/types/__init__.py | 444 -- .../cloud/dialogflow_v2beta1/types/agent.py | 492 --- .../dialogflow_v2beta1/types/answer_record.py | 392 -- .../dialogflow_v2beta1/types/audio_config.py | 507 --- .../cloud/dialogflow_v2beta1/types/context.py | 327 -- .../dialogflow_v2beta1/types/conversation.py | 462 -- .../types/conversation_event.py | 78 - .../types/conversation_profile.py | 818 ---- .../dialogflow_v2beta1/types/document.py | 525 --- .../dialogflow_v2beta1/types/entity_type.py | 586 --- .../dialogflow_v2beta1/types/environment.py | 459 -- .../cloud/dialogflow_v2beta1/types/gcs.py | 62 - .../types/human_agent_assistant_event.py | 69 - .../cloud/dialogflow_v2beta1/types/intent.py | 2124 ---------- .../types/knowledge_base.py | 257 -- .../dialogflow_v2beta1/types/participant.py | 1473 ------- .../cloud/dialogflow_v2beta1/types/session.py | 1151 ----- .../types/session_entity_type.py | 274 -- .../types/validation_result.py | 93 - .../cloud/dialogflow_v2beta1/types/webhook.py | 260 -- owl-bot-staging/v2beta1/mypy.ini | 3 - owl-bot-staging/v2beta1/noxfile.py | 132 - .../fixup_dialogflow_v2beta1_keywords.py | 263 -- owl-bot-staging/v2beta1/setup.py | 53 - 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 | 3145 -------------- .../dialogflow_v2beta1/test_answer_records.py | 1814 -------- .../gapic/dialogflow_v2beta1/test_contexts.py | 2595 ------------ .../test_conversation_profiles.py | 2459 ----------- .../dialogflow_v2beta1/test_conversations.py | 2848 ------------- .../dialogflow_v2beta1/test_documents.py | 2804 ------------- .../dialogflow_v2beta1/test_entity_types.py | 3580 ---------------- .../dialogflow_v2beta1/test_environments.py | 2420 ----------- .../gapic/dialogflow_v2beta1/test_intents.py | 3100 -------------- .../test_knowledge_bases.py | 2378 ----------- .../dialogflow_v2beta1/test_participants.py | 3710 ----------------- .../test_session_entity_types.py | 2369 ----------- .../gapic/dialogflow_v2beta1/test_sessions.py | 1403 ------- scripts/fixup_dialogflow_v2_keywords.py | 157 +- scripts/fixup_dialogflow_v2beta1_keywords.py | 169 +- .../services => tests}/__init__.py | 0 .../services => tests/unit}/__init__.py | 0 .../v2/tests => tests/unit/gapic}/__init__.py | 1 - tests/unit/gapic/dialogflow_v2/__init__.py | 1 - tests/unit/gapic/dialogflow_v2/test_agents.py | 595 +-- .../dialogflow_v2/test_answer_records.py | 404 +- .../unit/gapic/dialogflow_v2/test_contexts.py | 516 ++- .../test_conversation_profiles.py | 617 ++- .../gapic/dialogflow_v2/test_conversations.py | 535 ++- .../gapic/dialogflow_v2/test_documents.py | 522 ++- .../gapic/dialogflow_v2/test_entity_types.py | 659 +-- .../gapic/dialogflow_v2/test_environments.py | 1598 ++++++- .../gapic/dialogflow_v2/test_fulfillments.py | 795 ++-- .../unit/gapic/dialogflow_v2/test_intents.py | 641 +-- .../dialogflow_v2/test_knowledge_bases.py | 530 ++- .../gapic/dialogflow_v2/test_participants.py | 583 +-- .../test_session_entity_types.py | 526 ++- .../unit/gapic/dialogflow_v2/test_sessions.py | 348 +- .../unit/gapic/dialogflow_v2/test_versions.py | 1260 +++--- .../unit/gapic/dialogflow_v2beta1/__init__.py | 1 - .../gapic/dialogflow_v2beta1/test_agents.py | 597 +-- .../dialogflow_v2beta1/test_answer_records.py | 428 +- .../gapic/dialogflow_v2beta1/test_contexts.py | 516 ++- .../test_conversation_profiles.py | 617 ++- .../dialogflow_v2beta1/test_conversations.py | 574 ++- .../dialogflow_v2beta1/test_documents.py | 541 ++- .../dialogflow_v2beta1/test_entity_types.py | 673 +-- .../dialogflow_v2beta1/test_environments.py | 1649 ++++++-- .../dialogflow_v2beta1/test_fulfillments.py | 799 ++-- .../gapic/dialogflow_v2beta1/test_intents.py | 647 +-- .../test_knowledge_bases.py | 530 ++- .../dialogflow_v2beta1/test_participants.py | 675 +-- .../test_session_entity_types.py | 526 ++- .../gapic/dialogflow_v2beta1/test_sessions.py | 349 +- .../gapic/dialogflow_v2beta1/test_versions.py | 1260 +++--- 687 files changed, 23786 insertions(+), 183321 deletions(-) rename {owl-bot-staging/v2/docs => docs}/dialogflow_v2/fulfillments.rst (100%) rename {owl-bot-staging/v2/docs => docs}/dialogflow_v2/versions.rst (100%) rename {owl-bot-staging/v2beta1/docs => docs}/dialogflow_v2beta1/fulfillments.rst (100%) rename {owl-bot-staging/v2beta1/docs => docs}/dialogflow_v2beta1/versions.rst (100%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/gapic_metadata.json (100%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/__init__.py (92%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/async_client.py (81%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/client.py (83%) rename {owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1 => google/cloud/dialogflow_v2}/services/fulfillments/transports/__init__.py (81%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/transports/base.py (73%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py (83%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/__init__.py (93%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/async_client.py (81%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/client.py (82%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/pagers.py (86%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/transports/__init__.py (81%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/transports/base.py (67%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/transports/grpc.py (80%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py (80%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/types/fulfillment.py (77%) rename {owl-bot-staging/v2/google => google}/cloud/dialogflow_v2/types/version.py (79%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/gapic_metadata.json (100%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py (92%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py (81%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/client.py (83%) rename {owl-bot-staging/v2/google/cloud/dialogflow_v2 => google/cloud/dialogflow_v2beta1}/services/fulfillments/transports/__init__.py (81%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py (73%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py (83%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/__init__.py (93%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/async_client.py (81%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/client.py (82%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/pagers.py (86%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py (81%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/transports/base.py (67%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py (80%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py (80%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/types/fulfillment.py (77%) rename {owl-bot-staging/v2beta1/google => google}/cloud/dialogflow_v2beta1/types/version.py (79%) 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_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/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/index.rst delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/__init__.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/py.typed 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/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/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/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/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/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/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/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/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/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/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/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/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/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_event.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/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/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/scripts/fixup_dialogflow_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.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_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_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/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/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/index.rst delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.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/py.typed 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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/scripts/fixup_dialogflow_v2beta1_keywords.py delete mode 100644 owl-bot-staging/v2beta1/setup.py 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_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 rename {owl-bot-staging/v2/google/cloud/dialogflow_v2/services => tests}/__init__.py (100%) rename {owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services => tests/unit}/__init__.py (100%) rename {owl-bot-staging/v2/tests => tests/unit/gapic}/__init__.py (99%) rename {owl-bot-staging/v2/tests => tests}/unit/gapic/dialogflow_v2/test_fulfillments.py (70%) rename {owl-bot-staging/v2/tests => tests}/unit/gapic/dialogflow_v2/test_versions.py (67%) rename {owl-bot-staging/v2beta1/tests => tests}/unit/gapic/dialogflow_v2beta1/test_fulfillments.py (70%) rename {owl-bot-staging/v2beta1/tests => tests}/unit/gapic/dialogflow_v2beta1/test_versions.py (67%) diff --git a/docs/dialogflow_v2/agents.rst b/docs/dialogflow_v2/agents.rst index 63897cb22..8661ecd44 100644 --- a/docs/dialogflow_v2/agents.rst +++ b/docs/dialogflow_v2/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/answer_records.rst b/docs/dialogflow_v2/answer_records.rst index 02a390a71..20345f618 100644 --- a/docs/dialogflow_v2/answer_records.rst +++ b/docs/dialogflow_v2/answer_records.rst @@ -5,7 +5,6 @@ AnswerRecords :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.answer_records.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/contexts.rst b/docs/dialogflow_v2/contexts.rst index 2f4c1efd7..ab27d7b1e 100644 --- a/docs/dialogflow_v2/contexts.rst +++ b/docs/dialogflow_v2/contexts.rst @@ -5,7 +5,6 @@ Contexts :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.contexts.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/conversation_profiles.rst b/docs/dialogflow_v2/conversation_profiles.rst index 85eaab68d..e5c4cda45 100644 --- a/docs/dialogflow_v2/conversation_profiles.rst +++ b/docs/dialogflow_v2/conversation_profiles.rst @@ -5,7 +5,6 @@ ConversationProfiles :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/conversations.rst b/docs/dialogflow_v2/conversations.rst index 72a2eb66c..a288e3783 100644 --- a/docs/dialogflow_v2/conversations.rst +++ b/docs/dialogflow_v2/conversations.rst @@ -5,7 +5,6 @@ Conversations :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.conversations.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/documents.rst b/docs/dialogflow_v2/documents.rst index fa18a2320..c95415ace 100644 --- a/docs/dialogflow_v2/documents.rst +++ b/docs/dialogflow_v2/documents.rst @@ -5,7 +5,6 @@ Documents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.documents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/entity_types.rst b/docs/dialogflow_v2/entity_types.rst index 821b7fd71..82634156b 100644 --- a/docs/dialogflow_v2/entity_types.rst +++ b/docs/dialogflow_v2/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/environments.rst b/docs/dialogflow_v2/environments.rst index 3e769ee5d..e0ca6f7f7 100644 --- a/docs/dialogflow_v2/environments.rst +++ b/docs/dialogflow_v2/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.environments.pagers :members: :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst b/docs/dialogflow_v2/fulfillments.rst similarity index 100% rename from owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst rename to docs/dialogflow_v2/fulfillments.rst diff --git a/docs/dialogflow_v2/intents.rst b/docs/dialogflow_v2/intents.rst index c2a444ebf..8418cb20d 100644 --- a/docs/dialogflow_v2/intents.rst +++ b/docs/dialogflow_v2/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/knowledge_bases.rst b/docs/dialogflow_v2/knowledge_bases.rst index d3371043f..7440330af 100644 --- a/docs/dialogflow_v2/knowledge_bases.rst +++ b/docs/dialogflow_v2/knowledge_bases.rst @@ -5,7 +5,6 @@ KnowledgeBases :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/participants.rst b/docs/dialogflow_v2/participants.rst index 9f5eecedb..6ce8a2c52 100644 --- a/docs/dialogflow_v2/participants.rst +++ b/docs/dialogflow_v2/participants.rst @@ -5,7 +5,6 @@ Participants :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.participants.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/services.rst b/docs/dialogflow_v2/services.rst index 66405aac5..8bdbdfe41 100644 --- a/docs/dialogflow_v2/services.rst +++ b/docs/dialogflow_v2/services.rst @@ -11,8 +11,10 @@ Services for Google Cloud Dialogflow v2 API documents entity_types environments + fulfillments intents knowledge_bases participants session_entity_types sessions + versions diff --git a/docs/dialogflow_v2/session_entity_types.rst b/docs/dialogflow_v2/session_entity_types.rst index a3cfccbbd..e1d7bd321 100644 --- a/docs/dialogflow_v2/session_entity_types.rst +++ b/docs/dialogflow_v2/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.session_entity_types.pagers :members: :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst b/docs/dialogflow_v2/versions.rst similarity index 100% rename from owl-bot-staging/v2/docs/dialogflow_v2/versions.rst rename to docs/dialogflow_v2/versions.rst diff --git a/docs/dialogflow_v2beta1/agents.rst b/docs/dialogflow_v2beta1/agents.rst index 057032e4a..154fdf432 100644 --- a/docs/dialogflow_v2beta1/agents.rst +++ b/docs/dialogflow_v2beta1/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/answer_records.rst b/docs/dialogflow_v2beta1/answer_records.rst index 26d58d618..1f890c79c 100644 --- a/docs/dialogflow_v2beta1/answer_records.rst +++ b/docs/dialogflow_v2beta1/answer_records.rst @@ -5,7 +5,6 @@ AnswerRecords :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/contexts.rst b/docs/dialogflow_v2beta1/contexts.rst index 0568b2019..e6be19355 100644 --- a/docs/dialogflow_v2beta1/contexts.rst +++ b/docs/dialogflow_v2beta1/contexts.rst @@ -5,7 +5,6 @@ Contexts :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.contexts.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/conversation_profiles.rst b/docs/dialogflow_v2beta1/conversation_profiles.rst index f3ecaaa53..959fe3698 100644 --- a/docs/dialogflow_v2beta1/conversation_profiles.rst +++ b/docs/dialogflow_v2beta1/conversation_profiles.rst @@ -5,7 +5,6 @@ ConversationProfiles :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/conversations.rst b/docs/dialogflow_v2beta1/conversations.rst index fda02a6a1..60267bd79 100644 --- a/docs/dialogflow_v2beta1/conversations.rst +++ b/docs/dialogflow_v2beta1/conversations.rst @@ -5,7 +5,6 @@ Conversations :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.conversations.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/documents.rst b/docs/dialogflow_v2beta1/documents.rst index 9516f4254..7151feda6 100644 --- a/docs/dialogflow_v2beta1/documents.rst +++ b/docs/dialogflow_v2beta1/documents.rst @@ -5,7 +5,6 @@ Documents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.documents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/entity_types.rst b/docs/dialogflow_v2beta1/entity_types.rst index f7c940846..99defb836 100644 --- a/docs/dialogflow_v2beta1/entity_types.rst +++ b/docs/dialogflow_v2beta1/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/environments.rst b/docs/dialogflow_v2beta1/environments.rst index f55d2c24d..3c4d6f333 100644 --- a/docs/dialogflow_v2beta1/environments.rst +++ b/docs/dialogflow_v2beta1/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.environments.pagers :members: :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst b/docs/dialogflow_v2beta1/fulfillments.rst similarity index 100% rename from owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst rename to docs/dialogflow_v2beta1/fulfillments.rst diff --git a/docs/dialogflow_v2beta1/intents.rst b/docs/dialogflow_v2beta1/intents.rst index 2af6dbe49..50e85e80d 100644 --- a/docs/dialogflow_v2beta1/intents.rst +++ b/docs/dialogflow_v2beta1/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/knowledge_bases.rst b/docs/dialogflow_v2beta1/knowledge_bases.rst index 7d2696d24..70e0d5ab6 100644 --- a/docs/dialogflow_v2beta1/knowledge_bases.rst +++ b/docs/dialogflow_v2beta1/knowledge_bases.rst @@ -5,7 +5,6 @@ KnowledgeBases :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/participants.rst b/docs/dialogflow_v2beta1/participants.rst index 61590eb9d..b2a73ebe3 100644 --- a/docs/dialogflow_v2beta1/participants.rst +++ b/docs/dialogflow_v2beta1/participants.rst @@ -5,7 +5,6 @@ Participants :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.participants.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/services.rst b/docs/dialogflow_v2beta1/services.rst index 209363e0e..dc7790aa3 100644 --- a/docs/dialogflow_v2beta1/services.rst +++ b/docs/dialogflow_v2beta1/services.rst @@ -11,8 +11,10 @@ Services for Google Cloud Dialogflow v2beta1 API documents entity_types environments + fulfillments intents knowledge_bases participants session_entity_types sessions + versions diff --git a/docs/dialogflow_v2beta1/session_entity_types.rst b/docs/dialogflow_v2beta1/session_entity_types.rst index 113b7acfb..4fe3bcb31 100644 --- a/docs/dialogflow_v2beta1/session_entity_types.rst +++ b/docs/dialogflow_v2beta1/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers :members: :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst b/docs/dialogflow_v2beta1/versions.rst similarity index 100% rename from owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst rename to docs/dialogflow_v2beta1/versions.rst diff --git a/google/cloud/dialogflow/__init__.py b/google/cloud/dialogflow/__init__.py index a766e6b13..2e7f45779 100644 --- a/google/cloud/dialogflow/__init__.py +++ b/google/cloud/dialogflow/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,62 +14,71 @@ # limitations under the License. # -from google.cloud.dialogflow_v2.services.agents.async_client import AgentsAsyncClient from google.cloud.dialogflow_v2.services.agents.client import AgentsClient -from google.cloud.dialogflow_v2.services.answer_records.async_client import ( - AnswerRecordsAsyncClient, -) +from google.cloud.dialogflow_v2.services.agents.async_client import AgentsAsyncClient from google.cloud.dialogflow_v2.services.answer_records.client import ( AnswerRecordsClient, ) -from google.cloud.dialogflow_v2.services.contexts.async_client import ( - ContextsAsyncClient, +from google.cloud.dialogflow_v2.services.answer_records.async_client import ( + AnswerRecordsAsyncClient, ) from google.cloud.dialogflow_v2.services.contexts.client import ContextsClient -from google.cloud.dialogflow_v2.services.conversation_profiles.async_client import ( - ConversationProfilesAsyncClient, +from google.cloud.dialogflow_v2.services.contexts.async_client import ( + ContextsAsyncClient, ) from google.cloud.dialogflow_v2.services.conversation_profiles.client import ( ConversationProfilesClient, ) +from google.cloud.dialogflow_v2.services.conversation_profiles.async_client import ( + ConversationProfilesAsyncClient, +) +from google.cloud.dialogflow_v2.services.conversations.client import ConversationsClient from google.cloud.dialogflow_v2.services.conversations.async_client import ( ConversationsAsyncClient, ) -from google.cloud.dialogflow_v2.services.conversations.client import ConversationsClient +from google.cloud.dialogflow_v2.services.documents.client import DocumentsClient from google.cloud.dialogflow_v2.services.documents.async_client import ( DocumentsAsyncClient, ) -from google.cloud.dialogflow_v2.services.documents.client import DocumentsClient +from google.cloud.dialogflow_v2.services.entity_types.client import EntityTypesClient from google.cloud.dialogflow_v2.services.entity_types.async_client import ( EntityTypesAsyncClient, ) -from google.cloud.dialogflow_v2.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflow_v2.services.environments.client import EnvironmentsClient from google.cloud.dialogflow_v2.services.environments.async_client import ( EnvironmentsAsyncClient, ) -from google.cloud.dialogflow_v2.services.environments.client import EnvironmentsClient -from google.cloud.dialogflow_v2.services.intents.async_client import IntentsAsyncClient -from google.cloud.dialogflow_v2.services.intents.client import IntentsClient -from google.cloud.dialogflow_v2.services.knowledge_bases.async_client import ( - KnowledgeBasesAsyncClient, +from google.cloud.dialogflow_v2.services.fulfillments.client import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments.async_client import ( + FulfillmentsAsyncClient, ) +from google.cloud.dialogflow_v2.services.intents.client import IntentsClient +from google.cloud.dialogflow_v2.services.intents.async_client import IntentsAsyncClient from google.cloud.dialogflow_v2.services.knowledge_bases.client import ( KnowledgeBasesClient, ) -from google.cloud.dialogflow_v2.services.participants.async_client import ( - ParticipantsAsyncClient, +from google.cloud.dialogflow_v2.services.knowledge_bases.async_client import ( + KnowledgeBasesAsyncClient, ) from google.cloud.dialogflow_v2.services.participants.client import ParticipantsClient -from google.cloud.dialogflow_v2.services.session_entity_types.async_client import ( - SessionEntityTypesAsyncClient, +from google.cloud.dialogflow_v2.services.participants.async_client import ( + ParticipantsAsyncClient, ) from google.cloud.dialogflow_v2.services.session_entity_types.client import ( SessionEntityTypesClient, ) +from google.cloud.dialogflow_v2.services.session_entity_types.async_client import ( + SessionEntityTypesAsyncClient, +) +from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient from google.cloud.dialogflow_v2.services.sessions.async_client import ( SessionsAsyncClient, ) -from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient +from google.cloud.dialogflow_v2.services.versions.client import VersionsClient +from google.cloud.dialogflow_v2.services.versions.async_client import ( + VersionsAsyncClient, +) + from google.cloud.dialogflow_v2.types.agent import Agent from google.cloud.dialogflow_v2.types.agent import DeleteAgentRequest from google.cloud.dialogflow_v2.types.agent import ExportAgentRequest @@ -90,17 +98,17 @@ from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsRequest from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsResponse from google.cloud.dialogflow_v2.types.answer_record import UpdateAnswerRecordRequest -from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding from google.cloud.dialogflow_v2.types.audio_config import InputAudioConfig from google.cloud.dialogflow_v2.types.audio_config import OutputAudioConfig -from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding from google.cloud.dialogflow_v2.types.audio_config import SpeechContext -from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant from google.cloud.dialogflow_v2.types.audio_config import SpeechToTextConfig from google.cloud.dialogflow_v2.types.audio_config import SpeechWordInfo -from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender from google.cloud.dialogflow_v2.types.audio_config import SynthesizeSpeechConfig from google.cloud.dialogflow_v2.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant +from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender from google.cloud.dialogflow_v2.types.context import Context from google.cloud.dialogflow_v2.types.context import CreateContextRequest from google.cloud.dialogflow_v2.types.context import DeleteAllContextsRequest @@ -171,9 +179,19 @@ from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesRequest from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesResponse from google.cloud.dialogflow_v2.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflow_v2.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflow_v2.types.environment import DeleteEnvironmentRequest from google.cloud.dialogflow_v2.types.environment import Environment +from google.cloud.dialogflow_v2.types.environment import EnvironmentHistory +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentHistoryRequest +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentRequest from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsRequest from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflow_v2.types.environment import TextToSpeechSettings +from google.cloud.dialogflow_v2.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import Fulfillment +from google.cloud.dialogflow_v2.types.fulfillment import GetFulfillmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import UpdateFulfillmentRequest from google.cloud.dialogflow_v2.types.human_agent_assistant_event import ( HumanAgentAssistantEvent, ) @@ -185,10 +203,10 @@ from google.cloud.dialogflow_v2.types.intent import GetIntentRequest from google.cloud.dialogflow_v2.types.intent import Intent from google.cloud.dialogflow_v2.types.intent import IntentBatch -from google.cloud.dialogflow_v2.types.intent import IntentView from google.cloud.dialogflow_v2.types.intent import ListIntentsRequest from google.cloud.dialogflow_v2.types.intent import ListIntentsResponse from google.cloud.dialogflow_v2.types.intent import UpdateIntentRequest +from google.cloud.dialogflow_v2.types.intent import IntentView from google.cloud.dialogflow_v2.types.knowledge_base import CreateKnowledgeBaseRequest from google.cloud.dialogflow_v2.types.knowledge_base import DeleteKnowledgeBaseRequest from google.cloud.dialogflow_v2.types.knowledge_base import GetKnowledgeBaseRequest @@ -251,188 +269,216 @@ ) from google.cloud.dialogflow_v2.types.validation_result import ValidationError from google.cloud.dialogflow_v2.types.validation_result import ValidationResult +from google.cloud.dialogflow_v2.types.version import CreateVersionRequest +from google.cloud.dialogflow_v2.types.version import DeleteVersionRequest +from google.cloud.dialogflow_v2.types.version import GetVersionRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsResponse +from google.cloud.dialogflow_v2.types.version import UpdateVersionRequest +from google.cloud.dialogflow_v2.types.version import Version from google.cloud.dialogflow_v2.types.webhook import OriginalDetectIntentRequest from google.cloud.dialogflow_v2.types.webhook import WebhookRequest from google.cloud.dialogflow_v2.types.webhook import WebhookResponse __all__ = ( - "Agent", - "AgentAssistantFeedback", - "AgentAssistantRecord", - "AgentsAsyncClient", "AgentsClient", - "AnalyzeContentRequest", - "AnalyzeContentResponse", - "AnnotatedMessagePart", - "AnswerFeedback", - "AnswerRecord", - "AnswerRecordsAsyncClient", + "AgentsAsyncClient", "AnswerRecordsClient", - "ArticleAnswer", - "AudioEncoding", - "AutomatedAgentConfig", - "AutomatedAgentReply", - "BatchCreateEntitiesRequest", - "BatchDeleteEntitiesRequest", - "BatchDeleteEntityTypesRequest", - "BatchDeleteIntentsRequest", - "BatchUpdateEntitiesRequest", - "BatchUpdateEntityTypesRequest", - "BatchUpdateEntityTypesResponse", - "BatchUpdateIntentsRequest", - "BatchUpdateIntentsResponse", - "CompleteConversationRequest", - "Context", - "ContextsAsyncClient", + "AnswerRecordsAsyncClient", "ContextsClient", - "Conversation", - "ConversationEvent", - "ConversationPhoneNumber", - "ConversationProfile", - "ConversationProfilesAsyncClient", + "ContextsAsyncClient", "ConversationProfilesClient", - "ConversationsAsyncClient", + "ConversationProfilesAsyncClient", "ConversationsClient", - "CreateContextRequest", - "CreateConversationProfileRequest", - "CreateConversationRequest", - "CreateDocumentRequest", - "CreateEntityTypeRequest", - "CreateIntentRequest", - "CreateKnowledgeBaseRequest", - "CreateParticipantRequest", - "CreateSessionEntityTypeRequest", - "DeleteAgentRequest", - "DeleteAllContextsRequest", - "DeleteContextRequest", - "DeleteConversationProfileRequest", - "DeleteDocumentRequest", - "DeleteEntityTypeRequest", - "DeleteIntentRequest", - "DeleteKnowledgeBaseRequest", - "DeleteSessionEntityTypeRequest", - "DetectIntentRequest", - "DetectIntentResponse", - "Document", - "DocumentsAsyncClient", + "ConversationsAsyncClient", "DocumentsClient", - "DtmfParameters", - "EntityType", - "EntityTypeBatch", - "EntityTypesAsyncClient", + "DocumentsAsyncClient", "EntityTypesClient", - "Environment", - "EnvironmentsAsyncClient", + "EntityTypesAsyncClient", "EnvironmentsClient", - "EventInput", + "EnvironmentsAsyncClient", + "FulfillmentsClient", + "FulfillmentsAsyncClient", + "IntentsClient", + "IntentsAsyncClient", + "KnowledgeBasesClient", + "KnowledgeBasesAsyncClient", + "ParticipantsClient", + "ParticipantsAsyncClient", + "SessionEntityTypesClient", + "SessionEntityTypesAsyncClient", + "SessionsClient", + "SessionsAsyncClient", + "VersionsClient", + "VersionsAsyncClient", + "Agent", + "DeleteAgentRequest", "ExportAgentRequest", "ExportAgentResponse", - "FaqAnswer", "GetAgentRequest", - "GetContextRequest", - "GetConversationProfileRequest", - "GetConversationRequest", - "GetDocumentRequest", - "GetEntityTypeRequest", - "GetIntentRequest", - "GetKnowledgeBaseRequest", - "GetParticipantRequest", - "GetSessionEntityTypeRequest", "GetValidationResultRequest", - "HumanAgentAssistantConfig", - "HumanAgentAssistantEvent", - "HumanAgentHandoffConfig", "ImportAgentRequest", - "InputAudioConfig", - "Intent", - "IntentBatch", - "IntentView", - "IntentsAsyncClient", - "IntentsClient", - "KnowledgeBase", - "KnowledgeBasesAsyncClient", - "KnowledgeBasesClient", - "KnowledgeOperationMetadata", + "RestoreAgentRequest", + "SearchAgentsRequest", + "SearchAgentsResponse", + "SetAgentRequest", + "TrainAgentRequest", + "AgentAssistantFeedback", + "AgentAssistantRecord", + "AnswerFeedback", + "AnswerRecord", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", + "UpdateAnswerRecordRequest", + "InputAudioConfig", + "OutputAudioConfig", + "SpeechContext", + "SpeechToTextConfig", + "SpeechWordInfo", + "SynthesizeSpeechConfig", + "VoiceSelectionParams", + "AudioEncoding", + "OutputAudioEncoding", + "SpeechModelVariant", + "SsmlVoiceGender", + "Context", + "CreateContextRequest", + "DeleteAllContextsRequest", + "DeleteContextRequest", + "GetContextRequest", "ListContextsRequest", "ListContextsResponse", - "ListConversationProfilesRequest", - "ListConversationProfilesResponse", + "UpdateContextRequest", + "CompleteConversationRequest", + "Conversation", + "ConversationPhoneNumber", + "CreateConversationRequest", + "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "ListMessagesRequest", + "ListMessagesResponse", + "ConversationEvent", + "AutomatedAgentConfig", + "ConversationProfile", + "CreateConversationProfileRequest", + "DeleteConversationProfileRequest", + "GetConversationProfileRequest", + "HumanAgentAssistantConfig", + "HumanAgentHandoffConfig", + "ListConversationProfilesRequest", + "ListConversationProfilesResponse", + "LoggingConfig", + "NotificationConfig", + "SuggestionFeature", + "UpdateConversationProfileRequest", + "CreateDocumentRequest", + "DeleteDocumentRequest", + "Document", + "GetDocumentRequest", + "KnowledgeOperationMetadata", "ListDocumentsRequest", "ListDocumentsResponse", + "ReloadDocumentRequest", + "UpdateDocumentRequest", + "BatchCreateEntitiesRequest", + "BatchDeleteEntitiesRequest", + "BatchDeleteEntityTypesRequest", + "BatchUpdateEntitiesRequest", + "BatchUpdateEntityTypesRequest", + "BatchUpdateEntityTypesResponse", + "CreateEntityTypeRequest", + "DeleteEntityTypeRequest", + "EntityType", + "EntityTypeBatch", + "GetEntityTypeRequest", "ListEntityTypesRequest", "ListEntityTypesResponse", + "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", + "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", + "HumanAgentAssistantEvent", + "BatchDeleteIntentsRequest", + "BatchUpdateIntentsRequest", + "BatchUpdateIntentsResponse", + "CreateIntentRequest", + "DeleteIntentRequest", + "GetIntentRequest", + "Intent", + "IntentBatch", "ListIntentsRequest", "ListIntentsResponse", + "UpdateIntentRequest", + "IntentView", + "CreateKnowledgeBaseRequest", + "DeleteKnowledgeBaseRequest", + "GetKnowledgeBaseRequest", + "KnowledgeBase", "ListKnowledgeBasesRequest", "ListKnowledgeBasesResponse", - "ListMessagesRequest", - "ListMessagesResponse", + "UpdateKnowledgeBaseRequest", + "AnalyzeContentRequest", + "AnalyzeContentResponse", + "AnnotatedMessagePart", + "ArticleAnswer", + "AutomatedAgentReply", + "CreateParticipantRequest", + "DtmfParameters", + "FaqAnswer", + "GetParticipantRequest", "ListParticipantsRequest", "ListParticipantsResponse", - "ListSessionEntityTypesRequest", - "ListSessionEntityTypesResponse", - "LoggingConfig", "Message", "MessageAnnotation", - "NotificationConfig", - "OriginalDetectIntentRequest", "OutputAudio", - "OutputAudioConfig", - "OutputAudioEncoding", "Participant", - "ParticipantsAsyncClient", - "ParticipantsClient", + "SuggestArticlesRequest", + "SuggestArticlesResponse", + "SuggestFaqAnswersRequest", + "SuggestFaqAnswersResponse", + "SuggestionResult", + "UpdateParticipantRequest", + "DetectIntentRequest", + "DetectIntentResponse", + "EventInput", "QueryInput", "QueryParameters", "QueryResult", - "ReloadDocumentRequest", - "RestoreAgentRequest", - "SearchAgentsRequest", - "SearchAgentsResponse", "Sentiment", "SentimentAnalysisRequestConfig", "SentimentAnalysisResult", - "SessionEntityType", - "SessionEntityTypesAsyncClient", - "SessionEntityTypesClient", - "SessionsAsyncClient", - "SessionsClient", - "SetAgentRequest", - "SpeechContext", - "SpeechModelVariant", - "SpeechToTextConfig", - "SpeechWordInfo", - "SsmlVoiceGender", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", - "SuggestArticlesRequest", - "SuggestArticlesResponse", - "SuggestFaqAnswersRequest", - "SuggestFaqAnswersResponse", - "SuggestionFeature", - "SuggestionResult", - "SynthesizeSpeechConfig", "TextInput", - "TrainAgentRequest", - "UpdateAnswerRecordRequest", - "UpdateContextRequest", - "UpdateConversationProfileRequest", - "UpdateDocumentRequest", - "UpdateEntityTypeRequest", - "UpdateIntentRequest", - "UpdateKnowledgeBaseRequest", - "UpdateParticipantRequest", + "CreateSessionEntityTypeRequest", + "DeleteSessionEntityTypeRequest", + "GetSessionEntityTypeRequest", + "ListSessionEntityTypesRequest", + "ListSessionEntityTypesResponse", + "SessionEntityType", "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", - "VoiceSelectionParams", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", + "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", ) diff --git a/google/cloud/dialogflow_v2/__init__.py b/google/cloud/dialogflow_v2/__init__.py index 1bc06d15b..8d44eb9dd 100644 --- a/google/cloud/dialogflow_v2/__init__.py +++ b/google/cloud/dialogflow_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,36 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + from .types.agent import Agent from .types.agent import DeleteAgentRequest from .types.agent import ExportAgentRequest @@ -47,17 +64,17 @@ from .types.answer_record import ListAnswerRecordsRequest from .types.answer_record import ListAnswerRecordsResponse from .types.answer_record import UpdateAnswerRecordRequest -from .types.audio_config import AudioEncoding from .types.audio_config import InputAudioConfig from .types.audio_config import OutputAudioConfig -from .types.audio_config import OutputAudioEncoding from .types.audio_config import SpeechContext -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechToTextConfig from .types.audio_config import SpeechWordInfo -from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender from .types.context import Context from .types.context import CreateContextRequest from .types.context import DeleteAllContextsRequest @@ -112,9 +129,19 @@ from .types.entity_type import ListEntityTypesRequest from .types.entity_type import ListEntityTypesResponse from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest from .types.environment import ListEnvironmentsRequest from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest from .types.human_agent_assistant_event import HumanAgentAssistantEvent from .types.intent import BatchDeleteIntentsRequest from .types.intent import BatchUpdateIntentsRequest @@ -124,10 +151,10 @@ from .types.intent import GetIntentRequest from .types.intent import Intent from .types.intent import IntentBatch -from .types.intent import IntentView from .types.intent import ListIntentsRequest from .types.intent import ListIntentsResponse from .types.intent import UpdateIntentRequest +from .types.intent import IntentView from .types.knowledge_base import CreateKnowledgeBaseRequest from .types.knowledge_base import DeleteKnowledgeBaseRequest from .types.knowledge_base import GetKnowledgeBaseRequest @@ -178,12 +205,33 @@ 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", @@ -221,19 +269,23 @@ "CreateConversationRequest", "CreateDocumentRequest", "CreateEntityTypeRequest", + "CreateEnvironmentRequest", "CreateIntentRequest", "CreateKnowledgeBaseRequest", "CreateParticipantRequest", "CreateSessionEntityTypeRequest", + "CreateVersionRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", "DeleteEntityTypeRequest", + "DeleteEnvironmentRequest", "DeleteIntentRequest", "DeleteKnowledgeBaseRequest", "DeleteSessionEntityTypeRequest", + "DeleteVersionRequest", "DetectIntentRequest", "DetectIntentResponse", "Document", @@ -243,22 +295,29 @@ "EntityTypeBatch", "EntityTypesClient", "Environment", + "EnvironmentHistory", "EnvironmentsClient", "EventInput", "ExportAgentRequest", "ExportAgentResponse", "FaqAnswer", + "Fulfillment", + "FulfillmentsClient", "GetAgentRequest", "GetContextRequest", "GetConversationProfileRequest", "GetConversationRequest", "GetDocumentRequest", "GetEntityTypeRequest", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", + "GetFulfillmentRequest", "GetIntentRequest", "GetKnowledgeBaseRequest", "GetParticipantRequest", "GetSessionEntityTypeRequest", "GetValidationResultRequest", + "GetVersionRequest", "HumanAgentAssistantConfig", "HumanAgentAssistantEvent", "HumanAgentHandoffConfig", @@ -269,6 +328,7 @@ "IntentView", "IntentsClient", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -294,6 +354,8 @@ "ListParticipantsResponse", "ListSessionEntityTypesRequest", "ListSessionEntityTypesResponse", + "ListVersionsRequest", + "ListVersionsResponse", "LoggingConfig", "Message", "MessageAnnotation", @@ -334,20 +396,25 @@ "SuggestionResult", "SynthesizeSpeechConfig", "TextInput", + "TextToSpeechSettings", "TrainAgentRequest", "UpdateAnswerRecordRequest", "UpdateContextRequest", "UpdateConversationProfileRequest", "UpdateDocumentRequest", "UpdateEntityTypeRequest", + "UpdateEnvironmentRequest", + "UpdateFulfillmentRequest", "UpdateIntentRequest", "UpdateKnowledgeBaseRequest", "UpdateParticipantRequest", "UpdateSessionEntityTypeRequest", + "UpdateVersionRequest", "ValidationError", "ValidationResult", + "Version", + "VersionsClient", "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", ) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json b/google/cloud/dialogflow_v2/gapic_metadata.json similarity index 100% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json rename to google/cloud/dialogflow_v2/gapic_metadata.json diff --git a/google/cloud/dialogflow_v2/services/__init__.py b/google/cloud/dialogflow_v2/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/cloud/dialogflow_v2/services/__init__.py +++ b/google/cloud/dialogflow_v2/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/dialogflow_v2/services/agents/__init__.py b/google/cloud/dialogflow_v2/services/agents/__init__.py index 4bcbd7ac8..0501fa947 100644 --- a/google/cloud/dialogflow_v2/services/agents/__init__.py +++ b/google/cloud/dialogflow_v2/services/agents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AgentsClient from .async_client import AgentsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/agents/async_client.py b/google/cloud/dialogflow_v2/services/agents/async_client.py index 6ebcfe0ba..08fb842af 100644 --- a/google/cloud/dialogflow_v2/services/agents/async_client.py +++ b/google/cloud/dialogflow_v2/services/agents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport from .client import AgentsClient @@ -52,29 +49,25 @@ class AgentsAsyncClient: agent_path = staticmethod(AgentsClient.agent_path) parse_agent_path = staticmethod(AgentsClient.parse_agent_path) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( AgentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AgentsClient.common_folder_path) parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) parse_common_organization_path = staticmethod( AgentsClient.parse_common_organization_path ) - common_project_path = staticmethod(AgentsClient.common_project_path) parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -89,7 +82,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -106,7 +99,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AgentsTransport: The transport used by the client instance. @@ -120,12 +113,12 @@ def transport(self) -> AgentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AgentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -157,7 +150,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -187,7 +179,6 @@ async def get_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -223,7 +214,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -267,7 +257,6 @@ async def set_agent( This corresponds to the ``agent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -303,7 +292,6 @@ async def set_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -351,7 +339,6 @@ async def delete_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -372,7 +359,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -423,7 +409,6 @@ async def search_agents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -453,7 +438,6 @@ async def search_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -508,7 +492,6 @@ async def train_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -548,7 +531,6 @@ async def train_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -573,8 +555,8 @@ async def train_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -605,7 +587,6 @@ async def export_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -636,7 +617,6 @@ async def export_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -662,7 +642,7 @@ async def export_agent( response, self._client._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -698,7 +678,6 @@ async def import_agent( request (:class:`google.cloud.dialogflow_v2.types.ImportAgentRequest`): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -725,7 +704,6 @@ async def import_agent( """ # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -749,8 +727,8 @@ async def import_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -784,7 +762,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflow_v2.types.RestoreAgentRequest`): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -811,7 +788,6 @@ async def restore_agent( """ # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -835,8 +811,8 @@ async def restore_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -858,7 +834,6 @@ async def get_validation_result( request (:class:`google.cloud.dialogflow_v2.types.GetValidationResultRequest`): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -872,7 +847,6 @@ async def get_validation_result( """ # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2/services/agents/client.py b/google/cloud/dialogflow_v2/services/agents/client.py index 56cd648d7..d591e425d 100644 --- a/google/cloud/dialogflow_v2/services/agents/client.py +++ b/google/cloud/dialogflow_v2/services/agents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AgentsGrpcTransport from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class AgentsClientMeta(type): _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AgentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class AgentsClient(metaclass=AgentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,27 +151,28 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AgentsTransport: The transport used by the client instance. + AgentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/agent".format(project=project,) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match(r"^projects/(?P.+?)/agent$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -185,7 +185,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -196,7 +196,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -207,7 +207,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -232,12 +232,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AgentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -292,9 +292,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -306,12 +307,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -326,8 +329,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -364,7 +367,6 @@ def get_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -402,10 +404,8 @@ def get_agent( # there are no flattened fields. if not isinstance(request, agent.GetAgentRequest): request = agent.GetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -445,7 +445,6 @@ def set_agent( This corresponds to the ``agent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,10 +482,8 @@ def set_agent( # there are no flattened fields. if not isinstance(request, gcd_agent.SetAgentRequest): request = gcd_agent.SetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -530,7 +527,6 @@ def delete_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -553,10 +549,8 @@ def delete_agent( # there are no flattened fields. if not isinstance(request, agent.DeleteAgentRequest): request = agent.DeleteAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -603,7 +597,6 @@ def search_agents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -635,10 +628,8 @@ def search_agents( # there are no flattened fields. if not isinstance(request, agent.SearchAgentsRequest): request = agent.SearchAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -689,7 +680,6 @@ def train_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -731,10 +721,8 @@ def train_agent( # there are no flattened fields. if not isinstance(request, agent.TrainAgentRequest): request = agent.TrainAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -755,8 +743,8 @@ def train_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -787,7 +775,6 @@ def export_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -820,10 +807,8 @@ def export_agent( # there are no flattened fields. if not isinstance(request, agent.ExportAgentRequest): request = agent.ExportAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -845,7 +830,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -881,7 +866,6 @@ def import_agent( request (google.cloud.dialogflow_v2.types.ImportAgentRequest): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -908,7 +892,6 @@ def import_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ImportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -933,8 +916,8 @@ def import_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -968,7 +951,6 @@ def restore_agent( request (google.cloud.dialogflow_v2.types.RestoreAgentRequest): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,7 +977,6 @@ def restore_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.RestoreAgentRequest. # There's no risk of modifying the input as we've already verified @@ -1020,8 +1001,8 @@ def restore_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1043,7 +1024,6 @@ def get_validation_result( request (google.cloud.dialogflow_v2.types.GetValidationResultRequest): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1057,7 +1037,6 @@ def get_validation_result( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.GetValidationResultRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2/services/agents/pagers.py b/google/cloud/dialogflow_v2/services/agents/pagers.py index edb50660a..d8e3602be 100644 --- a/google/cloud/dialogflow_v2/services/agents/pagers.py +++ b/google/cloud/dialogflow_v2/services/agents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/agents/transports/__init__.py b/google/cloud/dialogflow_v2/services/agents/transports/__init__.py index dfed91927..ceadcd3aa 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/agents/transports/base.py b/google/cloud/dialogflow_v2/services/agents/transports/base.py index b41e474a7..e3e6bb8c5 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,6 +41,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -51,21 +61,24 @@ class AgentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -74,7 +87,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -88,29 +101,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -153,85 +213,78 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def get_agent( self, - ) -> typing.Callable[ - [agent.GetAgentRequest], - typing.Union[agent.Agent, typing.Awaitable[agent.Agent]], - ]: + ) -> Callable[[agent.GetAgentRequest], Union[agent.Agent, Awaitable[agent.Agent]]]: raise NotImplementedError() @property def set_agent( self, - ) -> typing.Callable[ - [gcd_agent.SetAgentRequest], - typing.Union[gcd_agent.Agent, typing.Awaitable[gcd_agent.Agent]], + ) -> Callable[ + [gcd_agent.SetAgentRequest], Union[gcd_agent.Agent, Awaitable[gcd_agent.Agent]] ]: raise NotImplementedError() @property def delete_agent( self, - ) -> typing.Callable[ - [agent.DeleteAgentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [agent.DeleteAgentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def search_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.SearchAgentsRequest], - typing.Union[ - agent.SearchAgentsResponse, typing.Awaitable[agent.SearchAgentsResponse] - ], + Union[agent.SearchAgentsResponse, Awaitable[agent.SearchAgentsResponse]], ]: raise NotImplementedError() @property def train_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.TrainAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def export_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ExportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def import_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ImportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def restore_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.RestoreAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def get_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetValidationResultRequest], - typing.Union[ + Union[ validation_result.ValidationResult, - typing.Awaitable[validation_result.ValidationResult], + Awaitable[validation_result.ValidationResult], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc.py index 3ace9db2e..281cb014b 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,9 +28,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -290,7 +290,7 @@ def set_agent(self) -> Callable[[gcd_agent.SetAgentRequest], gcd_agent.Agent]: return self._stubs["set_agent"] @property - def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: + def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty_pb2.Empty]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -309,7 +309,7 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -346,7 +346,9 @@ def search_agents( return self._stubs["search_agents"] @property - def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operation]: + def train_agent( + self, + ) -> Callable[[agent.TrainAgentRequest], operations_pb2.Operation]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -368,14 +370,14 @@ def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operatio self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ExportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a ZIP file. @@ -397,14 +399,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ImportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -439,14 +441,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], operations.Operation]: + ) -> Callable[[agent.RestoreAgentRequest], operations_pb2.Operation]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a ZIP file. @@ -479,7 +481,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py index 22f02de20..9fb73d4fb 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,9 +29,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO from .grpc import AgentsGrpcTransport @@ -58,7 +55,7 @@ class AgentsGrpcAsyncIOTransport(AgentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -300,7 +299,7 @@ def set_agent( @property def delete_agent( self, - ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -319,7 +318,7 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -358,7 +357,7 @@ def search_agents( @property def train_agent( self, - ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -380,14 +379,14 @@ def train_agent( self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a ZIP file. @@ -409,14 +408,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -451,14 +450,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a ZIP file. @@ -491,7 +490,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflow_v2/services/answer_records/__init__.py b/google/cloud/dialogflow_v2/services/answer_records/__init__.py index 7618f55a7..25960120e 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/__init__.py +++ b/google/cloud/dialogflow_v2/services/answer_records/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AnswerRecordsClient from .async_client import AnswerRecordsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/google/cloud/dialogflow_v2/services/answer_records/async_client.py index cd5148715..75452cd4f 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport from .client import AnswerRecordsClient @@ -52,31 +49,26 @@ class AnswerRecordsAsyncClient: parse_answer_record_path = staticmethod( AnswerRecordsClient.parse_answer_record_path ) - common_billing_account_path = staticmethod( AnswerRecordsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AnswerRecordsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) parse_common_folder_path = staticmethod( AnswerRecordsClient.parse_common_folder_path ) - common_organization_path = staticmethod( AnswerRecordsClient.common_organization_path ) parse_common_organization_path = staticmethod( AnswerRecordsClient.parse_common_organization_path ) - common_project_path = staticmethod(AnswerRecordsClient.common_project_path) parse_common_project_path = staticmethod( AnswerRecordsClient.parse_common_project_path ) - common_location_path = staticmethod(AnswerRecordsClient.common_location_path) parse_common_location_path = staticmethod( AnswerRecordsClient.parse_common_location_path @@ -84,7 +76,8 @@ class AnswerRecordsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AnswerRecordsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AnswerRecordsTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> AnswerRecordsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the answer records client. + """Instantiates the answer records client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AnswerRecordsClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def list_answer_records( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -209,7 +200,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -229,7 +220,6 @@ async def list_answer_records( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -264,7 +254,7 @@ async def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -287,7 +277,6 @@ async def update_answer_record( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -324,12 +313,11 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -346,7 +334,6 @@ async def update_answer_record( # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/answer_records/client.py b/google/cloud/dialogflow_v2/services/answer_records/client.py index 9940b63f1..d88d1d8bb 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AnswerRecordsGrpcTransport from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class AnswerRecordsClientMeta(type): _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AnswerRecordsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,23 +149,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AnswerRecordsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AnswerRecordsTransport: The transport used by the client instance. + AnswerRecordsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def answer_record_path(project: str, answer_record: str,) -> str: - """Return a fully-qualified answer_record string.""" + """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]: - """Parse a answer_record path into its component segments.""" + """Parses a answer_record path into its component segments.""" m = re.match( r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path ) @@ -174,7 +174,7 @@ def parse_answer_record_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -187,7 +187,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -198,7 +198,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -209,7 +209,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -220,7 +220,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -234,12 +234,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AnswerRecordsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the answer records client. + """Instantiates the answer records client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -294,9 +294,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -308,12 +309,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -328,8 +331,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -368,7 +371,6 @@ def list_answer_records( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -378,7 +380,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -400,10 +402,8 @@ def list_answer_records( # there are no flattened fields. if not isinstance(request, answer_record.ListAnswerRecordsRequest): request = answer_record.ListAnswerRecordsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -434,7 +434,7 @@ def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -457,7 +457,6 @@ def update_answer_record( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -494,12 +493,11 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -518,10 +516,8 @@ def update_answer_record( # there are no flattened fields. if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): request = gcd_answer_record.UpdateAnswerRecordRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/answer_records/pagers.py b/google/cloud/dialogflow_v2/services/answer_records/pagers.py index 6495fe2db..18ffae225 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/pagers.py +++ b/google/cloud/dialogflow_v2/services/answer_records/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py b/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py index bbb65cf15..e97f4f57d 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2/services/answer_records/transports/base.py index d82b61291..6e3503557 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AnswerRecordsTransport(abc.ABC): """Abstract transport class for AnswerRecords.""" @@ -47,21 +57,24 @@ class AnswerRecordsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -123,11 +183,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_answer_records( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.ListAnswerRecordsRequest], - typing.Union[ + Union[ answer_record.ListAnswerRecordsResponse, - typing.Awaitable[answer_record.ListAnswerRecordsResponse], + Awaitable[answer_record.ListAnswerRecordsResponse], ], ]: raise NotImplementedError() @@ -135,11 +195,10 @@ def list_answer_records( @property def update_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_answer_record.UpdateAnswerRecordRequest], - typing.Union[ - gcd_answer_record.AnswerRecord, - typing.Awaitable[gcd_answer_record.AnswerRecord], + Union[ + gcd_answer_record.AnswerRecord, Awaitable[gcd_answer_record.AnswerRecord] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py index 38373a7c5..5e7694260 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py index eec5d7448..002c9b9f5 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .grpc import AnswerRecordsGrpcTransport @@ -55,7 +52,7 @@ class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/contexts/__init__.py b/google/cloud/dialogflow_v2/services/contexts/__init__.py index 56b19b0f2..4c5791dcf 100644 --- a/google/cloud/dialogflow_v2/services/contexts/__init__.py +++ b/google/cloud/dialogflow_v2/services/contexts/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ContextsClient from .async_client import ContextsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/contexts/async_client.py b/google/cloud/dialogflow_v2/services/contexts/async_client.py index 9c318ef5e..d2c4bcd8e 100644 --- a/google/cloud/dialogflow_v2/services/contexts/async_client.py +++ b/google/cloud/dialogflow_v2/services/contexts/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport from .client import ContextsClient @@ -49,31 +46,27 @@ class ContextsAsyncClient: context_path = staticmethod(ContextsClient.context_path) parse_context_path = staticmethod(ContextsClient.parse_context_path) - common_billing_account_path = staticmethod( ContextsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ContextsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ContextsClient.common_folder_path) parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) - common_organization_path = staticmethod(ContextsClient.common_organization_path) parse_common_organization_path = staticmethod( ContextsClient.parse_common_organization_path ) - common_project_path = staticmethod(ContextsClient.common_project_path) parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) - common_location_path = staticmethod(ContextsClient.common_location_path) parse_common_location_path = staticmethod(ContextsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -88,7 +81,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -105,7 +98,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ContextsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ContextsTransport: The transport used by the client instance. @@ -119,12 +112,12 @@ def transport(self) -> ContextsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ContextsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the contexts client. + """Instantiates the contexts client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -156,7 +149,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ContextsClient( credentials=credentials, transport=transport, @@ -191,7 +183,6 @@ async def list_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -221,7 +212,6 @@ async def list_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -278,7 +268,6 @@ async def get_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -322,7 +311,6 @@ async def get_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -380,7 +368,6 @@ async def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -424,7 +411,6 @@ async def create_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -455,7 +441,7 @@ async def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -478,7 +464,6 @@ async def update_context( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -522,7 +507,6 @@ async def update_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -577,7 +561,6 @@ async def delete_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -598,7 +581,6 @@ async def delete_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -648,7 +630,6 @@ async def delete_all_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -669,7 +650,6 @@ async def delete_all_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/contexts/client.py b/google/cloud/dialogflow_v2/services/contexts/client.py index 6e32eab42..7880ab2c7 100644 --- a/google/cloud/dialogflow_v2/services/contexts/client.py +++ b/google/cloud/dialogflow_v2/services/contexts/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,9 +33,8 @@ from google.cloud.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ContextsGrpcTransport from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ContextsClientMeta(type): _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ContextsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -79,7 +76,8 @@ class ContextsClient(metaclass=ContextsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -113,7 +111,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -130,7 +129,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -149,23 +148,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ContextsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ContextsTransport: The transport used by the client instance. + ContextsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -174,7 +174,7 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -187,7 +187,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -198,7 +198,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -209,7 +209,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -220,7 +220,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -234,12 +234,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ContextsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the contexts client. + """Instantiates the contexts client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -294,9 +294,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -308,12 +309,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -328,8 +331,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -371,7 +374,6 @@ def list_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -403,10 +405,8 @@ def list_contexts( # there are no flattened fields. if not isinstance(request, context.ListContextsRequest): request = context.ListContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -459,7 +459,6 @@ def get_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -505,10 +504,8 @@ def get_context( # there are no flattened fields. if not isinstance(request, context.GetContextRequest): request = context.GetContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -562,7 +559,6 @@ def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -608,10 +604,8 @@ def create_context( # there are no flattened fields. if not isinstance(request, gcd_context.CreateContextRequest): request = gcd_context.CreateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -638,7 +632,7 @@ def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -661,7 +655,6 @@ def update_context( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +700,8 @@ def update_context( # there are no flattened fields. if not isinstance(request, gcd_context.UpdateContextRequest): request = gcd_context.UpdateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -761,7 +752,6 @@ def delete_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -784,10 +774,8 @@ def delete_context( # there are no flattened fields. if not isinstance(request, context.DeleteContextRequest): request = context.DeleteContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -833,7 +821,6 @@ def delete_all_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -856,10 +843,8 @@ def delete_all_contexts( # there are no flattened fields. if not isinstance(request, context.DeleteAllContextsRequest): request = context.DeleteAllContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/contexts/pagers.py b/google/cloud/dialogflow_v2/services/contexts/pagers.py index 90adad946..e61140a68 100644 --- a/google/cloud/dialogflow_v2/services/contexts/pagers.py +++ b/google/cloud/dialogflow_v2/services/contexts/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py b/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py index 7437034e4..d25eca3aa 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/base.py b/google/cloud/dialogflow_v2/services/contexts/transports/base.py index 350f2d7fc..07249b99d 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ContextsTransport(abc.ABC): """Abstract transport class for Contexts.""" @@ -48,21 +58,24 @@ class ContextsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -134,56 +194,53 @@ def _prep_wrapped_messages(self, client_info): @property def list_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.ListContextsRequest], - typing.Union[ - context.ListContextsResponse, typing.Awaitable[context.ListContextsResponse] - ], + Union[context.ListContextsResponse, Awaitable[context.ListContextsResponse]], ]: raise NotImplementedError() @property def get_context( self, - ) -> typing.Callable[ - [context.GetContextRequest], - typing.Union[context.Context, typing.Awaitable[context.Context]], + ) -> Callable[ + [context.GetContextRequest], Union[context.Context, Awaitable[context.Context]] ]: raise NotImplementedError() @property def create_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.CreateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def update_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.UpdateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def delete_context( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteContextRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def delete_all_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteAllContextsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py index 7e3153ef0..60884118a 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -329,7 +329,9 @@ def update_context( return self._stubs["update_context"] @property - def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty]: + def delete_context( + self, + ) -> Callable[[context.DeleteContextRequest], empty_pb2.Empty]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -348,14 +350,14 @@ def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], empty.Empty]: + ) -> Callable[[context.DeleteAllContextsRequest], empty_pb2.Empty]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -374,7 +376,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py index 3e5d003b5..a00089966 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO from .grpc import ContextsGrpcTransport @@ -55,7 +52,7 @@ class ContextsGrpcAsyncIOTransport(ContextsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -339,7 +338,7 @@ def update_context( @property def delete_context( self, - ) -> Callable[[context.DeleteContextRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteContextRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -358,14 +357,14 @@ def delete_context( self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -384,7 +383,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py b/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py index 9ab8de0b8..c0cb1cd03 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ConversationProfilesClient from .async_client import ConversationProfilesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py b/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py index e66165698..08003bf43 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.conversation_profiles import pagers @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport from .client import ConversationProfilesClient @@ -54,6 +51,12 @@ class ConversationProfilesAsyncClient: agent_path = staticmethod(ConversationProfilesClient.agent_path) parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod( + ConversationProfilesClient.conversation_model_path + ) + parse_conversation_model_path = staticmethod( + ConversationProfilesClient.parse_conversation_model_path + ) conversation_profile_path = staticmethod( ConversationProfilesClient.conversation_profile_path ) @@ -66,31 +69,26 @@ class ConversationProfilesAsyncClient: parse_knowledge_base_path = staticmethod( ConversationProfilesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( ConversationProfilesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationProfilesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationProfilesClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationProfilesClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationProfilesClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationProfilesClient.common_project_path) parse_common_project_path = staticmethod( ConversationProfilesClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationProfilesClient.common_location_path) parse_common_location_path = staticmethod( ConversationProfilesClient.parse_common_location_path @@ -98,7 +96,8 @@ class ConversationProfilesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -113,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -130,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationProfilesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ConversationProfilesTransport: The transport used by the client instance. @@ -145,12 +144,12 @@ def transport(self) -> ConversationProfilesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversation profiles client. + """Instantiates the conversation profiles client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -182,7 +181,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationProfilesClient( credentials=credentials, transport=transport, @@ -214,7 +212,6 @@ async def list_conversation_profiles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -244,7 +241,6 @@ async def list_conversation_profiles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -297,7 +293,6 @@ async def get_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -324,7 +319,6 @@ async def get_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -385,7 +379,6 @@ async def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,7 +405,6 @@ async def create_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -443,7 +435,7 @@ async def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -474,7 +466,6 @@ async def update_conversation_profile( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -501,7 +492,6 @@ async def update_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -554,7 +544,6 @@ async def delete_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -575,7 +564,6 @@ async def delete_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2/services/conversation_profiles/client.py index 4f0495e3e..3e7ac8707 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationProfilesGrpcTransport from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class ConversationProfilesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[ConversationProfilesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,34 +157,53 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationProfilesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ConversationProfilesTransport: The transport used by the client instance. + ConversationProfilesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/agent".format(project=project,) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match(r"^projects/(?P.+?)/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: - """Return a fully-qualified conversation_profile string.""" + """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]: - """Parse a conversation_profile path into its component segments.""" + """Parses a conversation_profile path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path, @@ -194,14 +212,14 @@ def parse_conversation_profile_path(path: str) -> Dict[str, str]: @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -210,14 +228,14 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def knowledge_base_path(project: str, knowledge_base: str,) -> str: - """Return a fully-qualified knowledge_base string.""" + """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]: - """Parse a knowledge_base path into its component segments.""" + """Parses a knowledge_base path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path ) @@ -225,7 +243,7 @@ def parse_knowledge_base_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -238,7 +256,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -249,7 +267,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -260,7 +278,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -271,7 +289,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -285,12 +303,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ConversationProfilesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversation profiles client. + """Instantiates the conversation profiles client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -345,9 +363,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -359,12 +378,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -379,8 +400,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -419,7 +440,6 @@ def list_conversation_profiles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -453,10 +473,8 @@ def list_conversation_profiles( request, conversation_profile.ListConversationProfilesRequest ): request = conversation_profile.ListConversationProfilesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -507,7 +525,6 @@ def get_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -536,10 +553,8 @@ def get_conversation_profile( # there are no flattened fields. if not isinstance(request, conversation_profile.GetConversationProfileRequest): request = conversation_profile.GetConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -596,7 +611,6 @@ def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -627,10 +641,8 @@ def create_conversation_profile( request, gcd_conversation_profile.CreateConversationProfileRequest ): request = gcd_conversation_profile.CreateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -659,7 +671,7 @@ def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -690,7 +702,6 @@ def update_conversation_profile( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -721,10 +732,8 @@ def update_conversation_profile( request, gcd_conversation_profile.UpdateConversationProfileRequest ): request = gcd_conversation_profile.UpdateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -775,7 +784,6 @@ def delete_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -800,10 +808,8 @@ def delete_conversation_profile( request, conversation_profile.DeleteConversationProfileRequest ): request = conversation_profile.DeleteConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py b/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py index 0e261b842..fe92fe799 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py index e97774bcf..f2a4e2203 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py index 5768948c2..affb92d5e 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import conversation_profile from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ConversationProfilesTransport(abc.ABC): """Abstract transport class for ConversationProfiles.""" @@ -50,21 +60,24 @@ class ConversationProfilesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_conversation_profiles( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.ListConversationProfilesRequest], - typing.Union[ + Union[ conversation_profile.ListConversationProfilesResponse, - typing.Awaitable[conversation_profile.ListConversationProfilesResponse], + Awaitable[conversation_profile.ListConversationProfilesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_conversation_profiles( @property def get_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.GetConversationProfileRequest], - typing.Union[ + Union[ conversation_profile.ConversationProfile, - typing.Awaitable[conversation_profile.ConversationProfile], + Awaitable[conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_conversation_profile( @property def create_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.CreateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_conversation_profile( @property def update_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.UpdateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.DeleteConversationProfileRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py index 9af6dd273..581dfa3bc 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,8 +28,7 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -358,7 +358,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> Callable[[conversation_profile.DeleteConversationProfileRequest], empty.Empty]: + ) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete conversation profile method over gRPC. Deletes the specified conversation profile. @@ -377,7 +379,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py index d6ec1c60c..f9493a17a 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,8 +29,7 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationProfilesGrpcTransport @@ -58,7 +55,7 @@ class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -363,7 +362,8 @@ def update_conversation_profile( def delete_conversation_profile( self, ) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], Awaitable[empty.Empty] + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete conversation profile method over gRPC. @@ -383,7 +383,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2/services/conversations/__init__.py b/google/cloud/dialogflow_v2/services/conversations/__init__.py index cce809abe..f6f6b90ff 100644 --- a/google/cloud/dialogflow_v2/services/conversations/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ConversationsClient from .async_client import ConversationsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/conversations/async_client.py b/google/cloud/dialogflow_v2/services/conversations/async_client.py index 7afd626e5..3a717bc8f 100644 --- a/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversations/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.conversations import pagers from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport from .client import ConversationsClient @@ -59,31 +56,26 @@ class ConversationsAsyncClient: ) message_path = staticmethod(ConversationsClient.message_path) parse_message_path = staticmethod(ConversationsClient.parse_message_path) - common_billing_account_path = staticmethod( ConversationsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationsClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationsClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationsClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationsClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationsClient.common_project_path) parse_common_project_path = staticmethod( ConversationsClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationsClient.common_location_path) parse_common_location_path = staticmethod( ConversationsClient.parse_common_location_path @@ -91,7 +83,8 @@ class ConversationsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -106,7 +99,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -123,7 +116,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ConversationsTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> ConversationsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversations client. + """Instantiates the conversations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationsClient( credentials=credentials, transport=transport, @@ -231,7 +223,6 @@ async def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -263,7 +254,6 @@ async def create_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -313,7 +303,6 @@ async def list_conversations( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -343,7 +332,6 @@ async def list_conversations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -395,7 +383,6 @@ async def get_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,7 +414,6 @@ async def get_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -476,7 +462,6 @@ async def complete_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -508,7 +493,6 @@ async def complete_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -559,7 +543,6 @@ async def list_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -589,7 +572,6 @@ async def list_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/conversations/client.py b/google/cloud/dialogflow_v2/services/conversations/client.py index 16e68f100..de0676b68 100644 --- a/google/cloud/dialogflow_v2/services/conversations/client.py +++ b/google/cloud/dialogflow_v2/services/conversations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationsGrpcTransport from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ConversationsClientMeta(type): _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ConversationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ConversationsClient(metaclass=ConversationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ConversationsTransport: The transport used by the client instance. + ConversationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def conversation_path(project: str, conversation: str,) -> str: - """Return a fully-qualified conversation string.""" + """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]: - """Parse a conversation path into its component segments.""" + """Parses a conversation path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)$", path ) @@ -175,14 +175,14 @@ def parse_conversation_path(path: str) -> Dict[str, str]: @staticmethod def conversation_profile_path(project: str, conversation_profile: str,) -> str: - """Return a fully-qualified conversation_profile string.""" + """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]: - """Parse a conversation_profile path into its component segments.""" + """Parses a conversation_profile path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path, @@ -191,14 +191,14 @@ def parse_conversation_profile_path(path: str) -> Dict[str, str]: @staticmethod def message_path(project: str, conversation: str, message: str,) -> str: - """Return a fully-qualified message string.""" + """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]: - """Parse a message path into its component segments.""" + """Parses a message path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path, @@ -207,7 +207,7 @@ def parse_message_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -220,7 +220,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -231,7 +231,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -242,7 +242,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -253,7 +253,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -267,12 +267,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ConversationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversations client. + """Instantiates the conversations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -327,9 +327,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -341,12 +342,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -361,8 +364,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -426,7 +429,6 @@ def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -460,10 +462,8 @@ def create_conversation( # there are no flattened fields. if not isinstance(request, gcd_conversation.CreateConversationRequest): request = gcd_conversation.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -509,7 +509,6 @@ def list_conversations( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -541,10 +540,8 @@ def list_conversations( # there are no flattened fields. if not isinstance(request, conversation.ListConversationsRequest): request = conversation.ListConversationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -592,7 +589,6 @@ def get_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -626,10 +622,8 @@ def get_conversation( # there are no flattened fields. if not isinstance(request, conversation.GetConversationRequest): request = conversation.GetConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -674,7 +668,6 @@ def complete_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -708,10 +701,8 @@ def complete_conversation( # there are no flattened fields. if not isinstance(request, conversation.CompleteConversationRequest): request = conversation.CompleteConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -758,7 +749,6 @@ def list_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -790,10 +780,8 @@ def list_messages( # there are no flattened fields. if not isinstance(request, conversation.ListMessagesRequest): request = conversation.ListMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/conversations/pagers.py b/google/cloud/dialogflow_v2/services/conversations/pagers.py index d770c7e8a..6296c621b 100644 --- a/google/cloud/dialogflow_v2/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2/services/conversations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py b/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py index 6597b6d01..2989914f7 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/base.py b/google/cloud/dialogflow_v2/services/conversations/transports/base.py index b96d45a4e..81b0c5a38 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ConversationsTransport(abc.ABC): """Abstract transport class for Conversations.""" @@ -47,21 +57,24 @@ class ConversationsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -132,23 +192,20 @@ def _prep_wrapped_messages(self, client_info): @property def create_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation.CreateConversationRequest], - typing.Union[ - gcd_conversation.Conversation, - typing.Awaitable[gcd_conversation.Conversation], - ], + Union[gcd_conversation.Conversation, Awaitable[gcd_conversation.Conversation]], ]: raise NotImplementedError() @property def list_conversations( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListConversationsRequest], - typing.Union[ + Union[ conversation.ListConversationsResponse, - typing.Awaitable[conversation.ListConversationsResponse], + Awaitable[conversation.ListConversationsResponse], ], ]: raise NotImplementedError() @@ -156,33 +213,29 @@ def list_conversations( @property def get_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.GetConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def complete_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.CompleteConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def list_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListMessagesRequest], - typing.Union[ + Union[ conversation.ListMessagesResponse, - typing.Awaitable[conversation.ListMessagesResponse], + Awaitable[conversation.ListMessagesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py index f3b8a5578..c7cf35d07 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py index 480cdcfae..947afd762 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -55,7 +52,7 @@ class ConversationsGrpcAsyncIOTransport(ConversationsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/documents/__init__.py b/google/cloud/dialogflow_v2/services/documents/__init__.py index 5f6db6815..f610c36b0 100644 --- a/google/cloud/dialogflow_v2/services/documents/__init__.py +++ b/google/cloud/dialogflow_v2/services/documents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DocumentsClient from .async_client import DocumentsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/documents/async_client.py b/google/cloud/dialogflow_v2/services/documents/async_client.py index 62632ef32..4eb8d9ce8 100644 --- a/google/cloud/dialogflow_v2/services/documents/async_client.py +++ b/google/cloud/dialogflow_v2/services/documents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,9 +31,8 @@ from google.cloud.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport from .client import DocumentsClient @@ -53,25 +50,20 @@ class DocumentsAsyncClient: document_path = staticmethod(DocumentsClient.document_path) parse_document_path = staticmethod(DocumentsClient.parse_document_path) - common_billing_account_path = staticmethod( DocumentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( DocumentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DocumentsClient.common_folder_path) parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentsClient.common_organization_path) parse_common_organization_path = staticmethod( DocumentsClient.parse_common_organization_path ) - common_project_path = staticmethod(DocumentsClient.common_project_path) parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) - common_location_path = staticmethod(DocumentsClient.common_location_path) parse_common_location_path = staticmethod( DocumentsClient.parse_common_location_path @@ -79,7 +71,8 @@ class DocumentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -94,7 +87,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -111,7 +104,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DocumentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: DocumentsTransport: The transport used by the client instance. @@ -125,12 +118,12 @@ def transport(self) -> DocumentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DocumentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the documents client. + """Instantiates the documents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DocumentsClient( credentials=credentials, transport=transport, @@ -194,7 +186,6 @@ async def list_documents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -224,7 +215,6 @@ async def list_documents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -276,7 +266,6 @@ async def get_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -310,7 +299,6 @@ async def get_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -367,7 +355,6 @@ async def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -405,7 +392,6 @@ async def create_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -465,7 +451,6 @@ async def delete_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -505,7 +490,6 @@ async def delete_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -530,7 +514,7 @@ async def delete_document( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -542,7 +526,7 @@ async def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -570,7 +554,6 @@ async def update_document( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -608,7 +591,6 @@ async def update_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -688,7 +670,6 @@ async def reload_document( This corresponds to the ``content_uri`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -726,7 +707,6 @@ async def reload_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if content_uri is not None: diff --git a/google/cloud/dialogflow_v2/services/documents/client.py b/google/cloud/dialogflow_v2/services/documents/client.py index 3863502ed..5de1b4341 100644 --- a/google/cloud/dialogflow_v2/services/documents/client.py +++ b/google/cloud/dialogflow_v2/services/documents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,9 +35,8 @@ from google.cloud.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DocumentsGrpcTransport from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class DocumentsClientMeta(type): _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[DocumentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class DocumentsClient(metaclass=DocumentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DocumentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DocumentsTransport: The transport used by the client instance. + DocumentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -178,7 +178,7 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -191,7 +191,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -224,7 +224,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -238,12 +238,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DocumentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the documents client. + """Instantiates the documents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -298,9 +298,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -312,12 +313,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -332,8 +335,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -372,7 +375,6 @@ def list_documents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -404,10 +406,8 @@ def list_documents( # there are no flattened fields. if not isinstance(request, document.ListDocumentsRequest): request = document.ListDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -455,7 +455,6 @@ def get_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,10 +490,8 @@ def get_document( # there are no flattened fields. if not isinstance(request, document.GetDocumentRequest): request = document.GetDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -547,7 +544,6 @@ def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -587,10 +583,8 @@ def create_document( # there are no flattened fields. if not isinstance(request, gcd_document.CreateDocumentRequest): request = gcd_document.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -646,7 +640,6 @@ def delete_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -688,10 +681,8 @@ def delete_document( # there are no flattened fields. if not isinstance(request, document.DeleteDocumentRequest): request = document.DeleteDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -712,7 +703,7 @@ def delete_document( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -724,7 +715,7 @@ def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -752,7 +743,6 @@ def update_document( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -792,10 +782,8 @@ def update_document( # there are no flattened fields. if not isinstance(request, gcd_document.UpdateDocumentRequest): request = gcd_document.UpdateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -871,7 +859,6 @@ def reload_document( This corresponds to the ``content_uri`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -911,10 +898,8 @@ def reload_document( # there are no flattened fields. if not isinstance(request, document.ReloadDocumentRequest): request = document.ReloadDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if content_uri is not None: diff --git a/google/cloud/dialogflow_v2/services/documents/pagers.py b/google/cloud/dialogflow_v2/services/documents/pagers.py index 9c5ec068a..b79d77b4a 100644 --- a/google/cloud/dialogflow_v2/services/documents/pagers.py +++ b/google/cloud/dialogflow_v2/services/documents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/documents/transports/__init__.py b/google/cloud/dialogflow_v2/services/documents/transports/__init__.py index af02ba19c..5d4948aa0 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/documents/transports/base.py b/google/cloud/dialogflow_v2/services/documents/transports/base.py index 39425610b..20350ece5 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class DocumentsTransport(abc.ABC): """Abstract transport class for Documents.""" @@ -49,21 +59,24 @@ class DocumentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -72,7 +85,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -140,11 +200,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ListDocumentsRequest], - typing.Union[ - document.ListDocumentsResponse, - typing.Awaitable[document.ListDocumentsResponse], + Union[ + document.ListDocumentsResponse, Awaitable[document.ListDocumentsResponse] ], ]: raise NotImplementedError() @@ -152,45 +211,45 @@ def list_documents( @property def get_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.GetDocumentRequest], - typing.Union[document.Document, typing.Awaitable[document.Document]], + Union[document.Document, Awaitable[document.Document]], ]: raise NotImplementedError() @property def create_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.CreateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.DeleteDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.UpdateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def reload_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ReloadDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc.py index e5cb89e6a..5a11c51e9 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -296,7 +296,7 @@ def get_document( @property def create_document( self, - ) -> Callable[[gcd_document.CreateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.CreateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the create document method over gRPC. Creates a new document. @@ -319,14 +319,14 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], operations.Operation]: + ) -> Callable[[document.DeleteDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -349,14 +349,14 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @property def update_document( self, - ) -> Callable[[gcd_document.UpdateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.UpdateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the update document method over gRPC. Updates the specified document. @@ -379,14 +379,14 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], operations.Operation]: + ) -> Callable[[document.ReloadDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -416,7 +416,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py index 105dd3739..e2173a7af 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO from .grpc import DocumentsGrpcTransport @@ -57,7 +54,7 @@ class DocumentsGrpcAsyncIOTransport(DocumentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -305,7 +304,7 @@ def get_document( def create_document( self, ) -> Callable[ - [gcd_document.CreateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.CreateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create document method over gRPC. @@ -329,14 +328,16 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.DeleteDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -359,7 +360,7 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @@ -367,7 +368,7 @@ def delete_document( def update_document( self, ) -> Callable[ - [gcd_document.UpdateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.UpdateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update document method over gRPC. @@ -391,14 +392,16 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ReloadDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -428,7 +431,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2/services/entity_types/__init__.py b/google/cloud/dialogflow_v2/services/entity_types/__init__.py index f52849c66..77cd53e9c 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/__init__.py +++ b/google/cloud/dialogflow_v2/services/entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EntityTypesClient from .async_client import EntityTypesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/entity_types/async_client.py b/google/cloud/dialogflow_v2/services/entity_types/async_client.py index a3c67d500..7f9e934cc 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/async_client.py +++ b/google/cloud/dialogflow_v2/services/entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,9 +31,8 @@ from google.cloud.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -53,27 +50,22 @@ class EntityTypesAsyncClient: entity_type_path = staticmethod(EntityTypesClient.entity_type_path) parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) - common_billing_account_path = staticmethod( EntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) - common_organization_path = staticmethod(EntityTypesClient.common_organization_path) parse_common_organization_path = staticmethod( EntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(EntityTypesClient.common_project_path) parse_common_project_path = staticmethod( EntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(EntityTypesClient.common_location_path) parse_common_location_path = staticmethod( EntityTypesClient.parse_common_location_path @@ -81,7 +73,8 @@ class EntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EntityTypesTransport: The transport used by the client instance. @@ -127,12 +120,12 @@ def transport(self) -> EntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -206,7 +198,6 @@ async def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +227,6 @@ async def list_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -301,7 +291,6 @@ async def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -341,7 +330,6 @@ async def get_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -406,7 +394,6 @@ async def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -446,7 +433,6 @@ async def create_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -505,7 +491,6 @@ async def update_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -545,7 +530,6 @@ async def update_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if language_code is not None: @@ -595,7 +579,6 @@ async def delete_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -616,7 +599,6 @@ async def delete_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -656,7 +638,6 @@ async def batch_update_entity_types( request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest`): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -674,7 +655,6 @@ async def batch_update_entity_types( """ # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -699,7 +679,7 @@ async def batch_update_entity_types( response, self._client._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -738,7 +718,6 @@ async def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -778,10 +757,8 @@ async def batch_delete_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if entity_type_names: request.entity_type_names.extend(entity_type_names) @@ -806,8 +783,8 @@ async def batch_delete_entity_types( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -856,7 +833,6 @@ async def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -896,12 +872,10 @@ async def batch_create_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -926,8 +900,8 @@ async def batch_create_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -980,7 +954,6 @@ async def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1020,12 +993,10 @@ async def batch_update_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -1050,8 +1021,8 @@ async def batch_update_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1103,7 +1074,6 @@ async def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1143,12 +1113,10 @@ async def batch_delete_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entity_values: request.entity_values.extend(entity_values) @@ -1173,8 +1141,8 @@ async def batch_delete_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2/services/entity_types/client.py b/google/cloud/dialogflow_v2/services/entity_types/client.py index 497f8a433..4eaf70536 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/client.py +++ b/google/cloud/dialogflow_v2/services/entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,9 +35,8 @@ from google.cloud.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class EntityTypesClientMeta(type): _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class EntityTypesClient(metaclass=EntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EntityTypesTransport: The transport used by the client instance. + EntityTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def entity_type_path(project: str, entity_type: str,) -> str: - """Return a fully-qualified entity_type string.""" + """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]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/entityTypes/(?P.+?)$", path ) @@ -177,7 +177,7 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -190,7 +190,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -201,7 +201,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -237,12 +237,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -297,9 +297,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -311,12 +312,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -331,8 +334,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -381,7 +384,6 @@ def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -413,10 +415,8 @@ def list_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.ListEntityTypesRequest): request = entity_type.ListEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -477,7 +477,6 @@ def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -519,10 +518,8 @@ def get_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.GetEntityTypeRequest): request = entity_type.GetEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -583,7 +580,6 @@ def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -625,10 +621,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): request = gcd_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -683,7 +677,6 @@ def update_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -725,10 +718,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): request = gcd_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if language_code is not None: @@ -774,7 +765,6 @@ def delete_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -797,10 +787,8 @@ def delete_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.DeleteEntityTypeRequest): request = entity_type.DeleteEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -836,7 +824,6 @@ def batch_update_entity_types( request (google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -854,7 +841,6 @@ def batch_update_entity_types( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a entity_type.BatchUpdateEntityTypesRequest. # There's no risk of modifying the input as we've already verified @@ -882,7 +868,7 @@ def batch_update_entity_types( response, self._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -921,7 +907,6 @@ def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -963,10 +948,8 @@ def batch_delete_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): request = entity_type.BatchDeleteEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type_names is not None: @@ -991,8 +974,8 @@ def batch_delete_entity_types( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1041,7 +1024,6 @@ def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1083,10 +1065,8 @@ def batch_create_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchCreateEntitiesRequest): request = entity_type.BatchCreateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1111,8 +1091,8 @@ def batch_create_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1165,7 +1145,6 @@ def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1207,10 +1186,8 @@ def batch_update_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): request = entity_type.BatchUpdateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1235,8 +1212,8 @@ def batch_update_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1288,7 +1265,6 @@ def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1330,10 +1306,8 @@ def batch_delete_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): request = entity_type.BatchDeleteEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_values is not None: @@ -1358,8 +1332,8 @@ def batch_delete_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2/services/entity_types/pagers.py b/google/cloud/dialogflow_v2/services/entity_types/pagers.py index 12d4aa9ed..2e4f1b75f 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/pagers.py +++ b/google/cloud/dialogflow_v2/services/entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py b/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py index 963959d1a..07ea82e1b 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/entity_types/transports/base.py index a2b32c6a1..ed8892ca7 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -50,21 +60,24 @@ class EntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -163,11 +223,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.ListEntityTypesRequest], - typing.Union[ + Union[ entity_type.ListEntityTypesResponse, - typing.Awaitable[entity_type.ListEntityTypesResponse], + Awaitable[entity_type.ListEntityTypesResponse], ], ]: raise NotImplementedError() @@ -175,85 +235,81 @@ def list_entity_types( @property def get_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.GetEntityTypeRequest], - typing.Union[entity_type.EntityType, typing.Awaitable[entity_type.EntityType]], + Union[entity_type.EntityType, Awaitable[entity_type.EntityType]], ]: raise NotImplementedError() @property def create_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def delete_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.DeleteEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def batch_update_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_create_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchCreateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_update_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py index cf9544f77..c486c108d 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +355,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty.Empty]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty_pb2.Empty]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -374,14 +374,16 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] @property def batch_update_entity_types( self, - ) -> Callable[[entity_type.BatchUpdateEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch update entity types method over gRPC. Updates/Creates multiple entity types in the specified agent. @@ -403,14 +405,16 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @property def batch_delete_entity_types( self, - ) -> Callable[[entity_type.BatchDeleteEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch delete entity types method over gRPC. Deletes entity types in the specified agent. @@ -432,14 +436,14 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @property def batch_create_entities( self, - ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch create entities method over gRPC. Creates multiple new entities in the specified entity type. @@ -461,14 +465,14 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @property def batch_update_entities( self, - ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch update entities method over gRPC. Updates or creates multiple entities in the specified entity @@ -492,14 +496,14 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @property def batch_delete_entities( self, - ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete entities method over gRPC. Deletes entities in the specified entity type. @@ -521,7 +525,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py index 7ce05d2e1..35b60cea1 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -58,7 +55,7 @@ class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -364,7 +363,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty.Empty]]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -383,7 +382,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] @@ -391,7 +390,7 @@ def delete_entity_type( def batch_update_entity_types( self, ) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entity types method over gRPC. @@ -414,7 +413,7 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @@ -422,7 +421,7 @@ def batch_update_entity_types( def batch_delete_entity_types( self, ) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entity types method over gRPC. @@ -445,7 +444,7 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @@ -453,7 +452,7 @@ def batch_delete_entity_types( def batch_create_entities( self, ) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchCreateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch create entities method over gRPC. @@ -476,7 +475,7 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @@ -484,7 +483,7 @@ def batch_create_entities( def batch_update_entities( self, ) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entities method over gRPC. @@ -509,7 +508,7 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @@ -517,7 +516,7 @@ def batch_update_entities( def batch_delete_entities( self, ) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entities method over gRPC. @@ -540,7 +539,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2/services/environments/__init__.py b/google/cloud/dialogflow_v2/services/environments/__init__.py index a67f2316d..0c2be9484 100644 --- a/google/cloud/dialogflow_v2/services/environments/__init__.py +++ b/google/cloud/dialogflow_v2/services/environments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EnvironmentsClient from .async_client import EnvironmentsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/environments/async_client.py b/google/cloud/dialogflow_v2/services/environments/async_client.py index acd916032..0c7a9d8de 100644 --- a/google/cloud/dialogflow_v2/services/environments/async_client.py +++ b/google/cloud/dialogflow_v2/services/environments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,15 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.types import environment - +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport from .client import EnvironmentsClient @@ -48,27 +47,24 @@ class EnvironmentsAsyncClient: environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_path) common_billing_account_path = staticmethod( EnvironmentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EnvironmentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) parse_common_organization_path = staticmethod( EnvironmentsClient.parse_common_organization_path ) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) parse_common_project_path = staticmethod( EnvironmentsClient.parse_common_project_path ) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) parse_common_location_path = staticmethod( EnvironmentsClient.parse_common_location_path @@ -76,7 +72,8 @@ class EnvironmentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EnvironmentsTransport: The transport used by the client instance. @@ -122,12 +119,12 @@ def transport(self) -> EnvironmentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -171,6 +167,7 @@ async def list_environments( self, request: environment.ListEnvironmentsRequest = None, *, + parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -182,7 +179,16 @@ async def list_environments( request (:class:`google.cloud.dialogflow_v2.types.ListEnvironmentsRequest`): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -199,9 +205,22 @@ async def list_environments( """ # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = environment.ListEnvironmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( @@ -228,6 +247,324 @@ async def list_environments( # Done; return the response. return response + async def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2/services/environments/client.py b/google/cloud/dialogflow_v2/services/environments/client.py index d54531fe3..705c558f3 100644 --- a/google/cloud/dialogflow_v2/services/environments/client.py +++ b/google/cloud/dialogflow_v2/services/environments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -34,7 +32,8 @@ from google.cloud.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.types import environment - +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EnvironmentsGrpcTransport from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport @@ -53,7 +52,7 @@ class EnvironmentsClientMeta(type): _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EnvironmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -78,7 +77,8 @@ class EnvironmentsClient(metaclass=EnvironmentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -112,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -129,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -148,31 +149,43 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EnvironmentsTransport: The transport used by the client instance. + EnvironmentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def environment_path(project: str, environment: str,) -> str: - """Return a fully-qualified environment string.""" + """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]: - """Parse a environment path into its component segments.""" + """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 common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -185,7 +198,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -196,7 +209,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -207,7 +220,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -218,7 +231,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -232,12 +245,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EnvironmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -292,9 +305,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -306,12 +320,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -326,8 +342,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -346,6 +362,7 @@ def list_environments( self, request: environment.ListEnvironmentsRequest = None, *, + parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -357,7 +374,16 @@ def list_environments( request (google.cloud.dialogflow_v2.types.ListEnvironmentsRequest): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (str): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -374,6 +400,14 @@ def list_environments( """ # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a environment.ListEnvironmentsRequest. @@ -381,6 +415,10 @@ def list_environments( # there are no flattened fields. if not isinstance(request, environment.ListEnvironmentsRequest): request = environment.ListEnvironmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -404,6 +442,329 @@ def list_environments( # Done; return the response. return response + def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2/services/environments/pagers.py b/google/cloud/dialogflow_v2/services/environments/pagers.py index ea6aa5567..426fc8f49 100644 --- a/google/cloud/dialogflow_v2/services/environments/pagers.py +++ b/google/cloud/dialogflow_v2/services/environments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -155,3 +153,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """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) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2/services/environments/transports/__init__.py b/google/cloud/dialogflow_v2/services/environments/transports/__init__.py index aff44bcdd..c72efee48 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/environments/transports/base.py b/google/cloud/dialogflow_v2/services/environments/transports/base.py index 35fd89eb7..beb636a3d 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -46,21 +57,24 @@ class EnvironmentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -69,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -83,45 +97,156 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.list_environments: gapic_v1.method.wrap_method( self.list_environments, default_timeout=None, client_info=client_info, ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, default_timeout=None, client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, default_timeout=None, client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, default_timeout=None, client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, default_timeout=None, client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), } @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def delete_environment( + self, + ) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, Awaitable[environment.EnvironmentHistory] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc.py index fd702da8b..ca713c98d 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -65,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -175,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -206,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -251,5 +252,149 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[[environment.GetEnvironmentRequest], environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[[environment.CreateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[[environment.UpdateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], environment.EnvironmentHistory + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py index f6c738c97..93f066c99 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -54,7 +52,7 @@ class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -81,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -95,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -109,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -167,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -256,5 +256,156 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory], + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py b/google/cloud/dialogflow_v2/services/fulfillments/__init__.py similarity index 92% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py rename to google/cloud/dialogflow_v2/services/fulfillments/__init__.py index 95fd359ef..6bade52dd 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/__init__.py @@ -17,6 +17,6 @@ from .async_client import FulfillmentsAsyncClient __all__ = ( - 'FulfillmentsClient', - 'FulfillmentsAsyncClient', + "FulfillmentsClient", + "FulfillmentsAsyncClient", ) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py b/google/cloud/dialogflow_v2/services/fulfillments/async_client.py similarity index 81% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py rename to google/cloud/dialogflow_v2/services/fulfillments/async_client.py index dff171a22..28fb7fc0b 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/async_client.py @@ -19,12 +19,12 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.types import fulfillment from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment @@ -46,16 +46,26 @@ class FulfillmentsAsyncClient: 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_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) + 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) + 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) + parse_common_location_path = staticmethod( + FulfillmentsClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -99,14 +109,18 @@ def transport(self) -> FulfillmentsTransport: """ return self._client.transport - get_transport_class = functools.partial(type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient)) + get_transport_class = functools.partial( + type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the fulfillments client. Args: @@ -144,17 +158,17 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def get_fulfillment(self, - request: fulfillment.GetFulfillmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: + async def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: r"""Retrieves the fulfillment. Args: @@ -195,8 +209,10 @@ async def get_fulfillment(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = fulfillment.GetFulfillmentRequest(request) @@ -216,31 +232,25 @@ async def get_fulfillment(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def update_fulfillment(self, - request: gcd_fulfillment.UpdateFulfillmentRequest = None, - *, - fulfillment: gcd_fulfillment.Fulfillment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: + async def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: r"""Updates the fulfillment. Args: @@ -287,8 +297,10 @@ async def update_fulfillment(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_fulfillment.UpdateFulfillmentRequest(request) @@ -310,26 +322,18 @@ async def update_fulfillment(self, # 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), - )), + 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, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -340,6 +344,4 @@ async def update_fulfillment(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FulfillmentsAsyncClient", -) +__all__ = ("FulfillmentsAsyncClient",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py b/google/cloud/dialogflow_v2/services/fulfillments/client.py similarity index 83% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py rename to google/cloud/dialogflow_v2/services/fulfillments/client.py index e0e36ef7a..c8ed49eab 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/client.py @@ -21,14 +21,14 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.types import fulfillment from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment @@ -45,13 +45,12 @@ class FulfillmentsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] _transport_registry["grpc"] = FulfillmentsGrpcTransport _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[FulfillmentsTransport]: + def get_transport_class(cls, label: str = None,) -> Type[FulfillmentsTransport]: """Returns an appropriate transport class. Args: @@ -141,8 +140,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: FulfillmentsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -161,75 +159,81 @@ def transport(self) -> FulfillmentsTransport: @staticmethod def fulfillment_path(project: str,) -> str: """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) + return "projects/{project}/agent/fulfillment".format(project=project,) @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format(folder=folder,) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format(organization=organization,) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format(project=project,) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FulfillmentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the fulfillments client. Args: @@ -273,7 +277,9 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) client_cert_source_func = None is_mtls = False @@ -314,8 +320,10 @@ def __init__(self, *, if isinstance(transport, FulfillmentsTransport): # transport is a FulfillmentsTransport instance. if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -334,14 +342,15 @@ def __init__(self, *, client_info=client_info, ) - def get_fulfillment(self, - request: fulfillment.GetFulfillmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: + def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: r"""Retrieves the fulfillment. Args: @@ -382,8 +391,10 @@ def get_fulfillment(self, # 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.') + 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. @@ -403,31 +414,25 @@ def get_fulfillment(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def update_fulfillment(self, - request: gcd_fulfillment.UpdateFulfillmentRequest = None, - *, - fulfillment: gcd_fulfillment.Fulfillment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: + def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: r"""Updates the fulfillment. Args: @@ -474,8 +479,10 @@ def update_fulfillment(self, # 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.') + 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. @@ -497,26 +504,18 @@ def update_fulfillment(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("fulfillment.name", request.fulfillment.name),) + ), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -527,6 +526,4 @@ def update_fulfillment(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FulfillmentsClient", -) +__all__ = ("FulfillmentsClient",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py similarity index 81% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py rename to google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py index 4b41f9212..d822b662b 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py @@ -23,11 +23,11 @@ # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] -_transport_registry['grpc'] = FulfillmentsGrpcTransport -_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport +_transport_registry["grpc"] = FulfillmentsGrpcTransport +_transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport __all__ = ( - 'FulfillmentsTransport', - 'FulfillmentsGrpcTransport', - 'FulfillmentsGrpcAsyncIOTransport', + "FulfillmentsTransport", + "FulfillmentsGrpcTransport", + "FulfillmentsGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py similarity index 73% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py rename to google/cloud/dialogflow_v2/services/fulfillments/transports/base.py index 5ffb71f97..750cc4860 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py @@ -21,7 +21,7 @@ import google.auth # type: ignore import google.api_core # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -31,7 +31,7 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', + "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: @@ -53,21 +53,23 @@ class FulfillmentsTransport(abc.ABC): """Abstract transport class for Fulfillments.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ) - DEFAULT_HOST: str = 'dialogflow.googleapis.com' + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -91,8 +93,8 @@ def __init__( your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) @@ -103,17 +105,19 @@ def __init__( # 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") + 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 - ) + 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) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials @@ -125,7 +129,9 @@ def __init__( # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" scopes_kwargs = {} @@ -142,7 +148,9 @@ def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[ # TODO: Remove this function once google-api-core >= 1.26.0 is required @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} @@ -163,36 +171,30 @@ 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.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, + self.update_fulfillment, default_timeout=None, client_info=client_info, ), - } + } @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - Union[ - fulfillment.Fulfillment, - Awaitable[fulfillment.Fulfillment] - ]]: + 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] - ]]: + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[gcd_fulfillment.Fulfillment, Awaitable[gcd_fulfillment.Fulfillment]], + ]: raise NotImplementedError() -__all__ = ( - 'FulfillmentsTransport', -) +__all__ = ("FulfillmentsTransport",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py similarity index 83% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py rename to google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py index 6330ba94a..8eb7fd8f7 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py @@ -16,9 +16,9 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -42,21 +42,24 @@ class FulfillmentsGrpcTransport(FulfillmentsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -168,13 +171,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -209,7 +214,7 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) @property @@ -219,9 +224,9 @@ def grpc_channel(self) -> grpc.Channel: return self._grpc_channel @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - fulfillment.Fulfillment]: + def get_fulfillment( + self, + ) -> Callable[[fulfillment.GetFulfillmentRequest], fulfillment.Fulfillment]: r"""Return a callable for the get fulfillment method over gRPC. Retrieves the fulfillment. @@ -236,18 +241,20 @@ def get_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["get_fulfillment"] @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - gcd_fulfillment.Fulfillment]: + 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. @@ -262,15 +269,13 @@ def update_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["update_fulfillment"] -__all__ = ( - 'FulfillmentsGrpcTransport', -) +__all__ = ("FulfillmentsGrpcTransport",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py rename to google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py index 6a7c6562d..b0f1afd0f 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py @@ -16,13 +16,13 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version -import grpc # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import fulfillment @@ -49,13 +49,15 @@ class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -86,22 +88,24 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -223,9 +227,11 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - Awaitable[fulfillment.Fulfillment]]: + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], Awaitable[fulfillment.Fulfillment] + ]: r"""Return a callable for the get fulfillment method over gRPC. Retrieves the fulfillment. @@ -240,18 +246,21 @@ def get_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["get_fulfillment"] @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - Awaitable[gcd_fulfillment.Fulfillment]]: + 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. @@ -266,15 +275,13 @@ def update_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["update_fulfillment"] -__all__ = ( - 'FulfillmentsGrpcAsyncIOTransport', -) +__all__ = ("FulfillmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2/services/intents/__init__.py b/google/cloud/dialogflow_v2/services/intents/__init__.py index 8719a9b64..5a2c263cf 100644 --- a/google/cloud/dialogflow_v2/services/intents/__init__.py +++ b/google/cloud/dialogflow_v2/services/intents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import IntentsClient from .async_client import IntentsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/intents/async_client.py b/google/cloud/dialogflow_v2/services/intents/async_client.py index 2d1ba2aa9..525e28976 100644 --- a/google/cloud/dialogflow_v2/services/intents/async_client.py +++ b/google/cloud/dialogflow_v2/services/intents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,10 +32,9 @@ from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -55,31 +52,27 @@ class IntentsAsyncClient: parse_context_path = staticmethod(IntentsClient.parse_context_path) intent_path = staticmethod(IntentsClient.intent_path) parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod( IntentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( IntentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(IntentsClient.common_folder_path) parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) parse_common_organization_path = staticmethod( IntentsClient.parse_common_organization_path ) - common_project_path = staticmethod(IntentsClient.common_project_path) parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -94,7 +87,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -111,7 +104,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: IntentsTransport: The transport used by the client instance. @@ -125,12 +118,12 @@ def transport(self) -> IntentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, IntentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -204,7 +196,6 @@ async def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -234,7 +225,6 @@ async def list_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -299,7 +289,6 @@ async def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -335,7 +324,6 @@ async def get_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -400,7 +388,6 @@ async def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -436,7 +423,6 @@ async def create_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -470,7 +456,7 @@ async def update_intent( *, intent: gcd_intent.Intent = None, language_code: str = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -503,7 +489,6 @@ async def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -539,7 +524,6 @@ async def update_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if language_code is not None: @@ -594,7 +578,6 @@ async def delete_intent( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -615,7 +598,6 @@ async def delete_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -682,7 +664,6 @@ async def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -713,7 +694,6 @@ async def batch_update_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -743,7 +723,7 @@ async def batch_update_intents( response, self._client._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -782,7 +762,6 @@ async def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -822,10 +801,8 @@ async def batch_delete_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if intents: request.intents.extend(intents) @@ -850,8 +827,8 @@ async def batch_delete_intents( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2/services/intents/client.py b/google/cloud/dialogflow_v2/services/intents/client.py index fd249f7fc..635cb1104 100644 --- a/google/cloud/dialogflow_v2/services/intents/client.py +++ b/google/cloud/dialogflow_v2/services/intents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,10 +36,9 @@ from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class IntentsClientMeta(type): _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IntentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class IntentsClient(metaclass=IntentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - IntentsTransport: The transport used by the client instance. + IntentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -178,20 +178,20 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -204,7 +204,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -215,7 +215,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -226,7 +226,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -237,7 +237,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -251,12 +251,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IntentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -311,9 +311,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -325,12 +326,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -345,8 +348,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -395,7 +398,6 @@ def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,10 +429,8 @@ def list_intents( # there are no flattened fields. if not isinstance(request, intent.ListIntentsRequest): request = intent.ListIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -491,7 +491,6 @@ def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -529,10 +528,8 @@ def get_intent( # there are no flattened fields. if not isinstance(request, intent.GetIntentRequest): request = intent.GetIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -593,7 +590,6 @@ def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -631,10 +627,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.CreateIntentRequest): request = gcd_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -664,7 +658,7 @@ def update_intent( *, intent: gcd_intent.Intent = None, language_code: str = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -697,7 +691,6 @@ def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -735,10 +728,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.UpdateIntentRequest): request = gcd_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if language_code is not None: @@ -789,7 +780,6 @@ def delete_intent( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -812,10 +802,8 @@ def delete_intent( # there are no flattened fields. if not isinstance(request, intent.DeleteIntentRequest): request = intent.DeleteIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -878,7 +866,6 @@ def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -911,10 +898,8 @@ def batch_update_intents( # there are no flattened fields. if not isinstance(request, intent.BatchUpdateIntentsRequest): request = intent.BatchUpdateIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -940,7 +925,7 @@ def batch_update_intents( response, self._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -979,7 +964,6 @@ def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1021,10 +1005,8 @@ def batch_delete_intents( # there are no flattened fields. if not isinstance(request, intent.BatchDeleteIntentsRequest): request = intent.BatchDeleteIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intents is not None: @@ -1047,8 +1029,8 @@ def batch_delete_intents( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2/services/intents/pagers.py b/google/cloud/dialogflow_v2/services/intents/pagers.py index d19ace9a4..5e9b67d52 100644 --- a/google/cloud/dialogflow_v2/services/intents/pagers.py +++ b/google/cloud/dialogflow_v2/services/intents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/intents/transports/__init__.py b/google/cloud/dialogflow_v2/services/intents/transports/__init__.py index 41fde33b5..974a58103 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/intents/transports/base.py b/google/cloud/dialogflow_v2/services/intents/transports/base.py index 57253e26f..31e64643a 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -50,21 +60,24 @@ class IntentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -148,65 +208,61 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.ListIntentsRequest], - typing.Union[ - intent.ListIntentsResponse, typing.Awaitable[intent.ListIntentsResponse] - ], + Union[intent.ListIntentsResponse, Awaitable[intent.ListIntentsResponse]], ]: raise NotImplementedError() @property def get_intent( self, - ) -> typing.Callable[ - [intent.GetIntentRequest], - typing.Union[intent.Intent, typing.Awaitable[intent.Intent]], + ) -> Callable[ + [intent.GetIntentRequest], Union[intent.Intent, Awaitable[intent.Intent]] ]: raise NotImplementedError() @property def create_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.CreateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.UpdateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def delete_intent( self, - ) -> typing.Callable[ - [intent.DeleteIntentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [intent.DeleteIntentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def batch_update_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchUpdateIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchDeleteIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc.py index 605e3f42f..ce1c9d409 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -344,7 +344,7 @@ def update_intent( return self._stubs["update_intent"] @property - def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: + def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty_pb2.Empty]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent and its direct or @@ -364,14 +364,14 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchUpdateIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -393,14 +393,14 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchDeleteIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -422,7 +422,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py index 4c2719a16..35838fa40 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -57,7 +54,7 @@ class IntentsGrpcAsyncIOTransport(IntentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -354,7 +353,7 @@ def update_intent( @property def delete_intent( self, - ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent and its direct or @@ -374,14 +373,16 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchUpdateIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -403,14 +404,16 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchDeleteIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -432,7 +435,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py b/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py index be24a37d1..24204c982 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import KnowledgeBasesClient from .async_client import KnowledgeBasesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py b/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py index 33d074e30..3a047d909 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport from .client import KnowledgeBasesClient @@ -52,31 +49,26 @@ class KnowledgeBasesAsyncClient: parse_knowledge_base_path = staticmethod( KnowledgeBasesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( KnowledgeBasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( KnowledgeBasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) parse_common_folder_path = staticmethod( KnowledgeBasesClient.parse_common_folder_path ) - common_organization_path = staticmethod( KnowledgeBasesClient.common_organization_path ) parse_common_organization_path = staticmethod( KnowledgeBasesClient.parse_common_organization_path ) - common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) parse_common_project_path = staticmethod( KnowledgeBasesClient.parse_common_project_path ) - common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) parse_common_location_path = staticmethod( KnowledgeBasesClient.parse_common_location_path @@ -84,7 +76,8 @@ class KnowledgeBasesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> KnowledgeBasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: KnowledgeBasesTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> KnowledgeBasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the knowledge bases client. + """Instantiates the knowledge bases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = KnowledgeBasesClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def list_knowledge_bases( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -229,7 +220,6 @@ async def list_knowledge_bases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -282,7 +272,6 @@ async def get_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -319,7 +308,6 @@ async def get_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -374,7 +362,6 @@ async def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -411,7 +398,6 @@ async def create_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -460,7 +446,6 @@ async def delete_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -481,7 +466,6 @@ async def delete_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -509,7 +493,7 @@ async def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -535,7 +519,6 @@ async def update_knowledge_base( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -572,7 +555,6 @@ async def update_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/client.py b/google/cloud/dialogflow_v2/services/knowledge_bases/client.py index d5f171ef9..2275faaca 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/client.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KnowledgeBasesGrpcTransport from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class KnowledgeBasesClientMeta(type): _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[KnowledgeBasesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,23 +151,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> KnowledgeBasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - KnowledgeBasesTransport: The transport used by the client instance. + KnowledgeBasesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def knowledge_base_path(project: str, knowledge_base: str,) -> str: - """Return a fully-qualified knowledge_base string.""" + """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]: - """Parse a knowledge_base path into its component segments.""" + """Parses a knowledge_base path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path ) @@ -176,7 +176,7 @@ def parse_knowledge_base_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -189,7 +189,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -200,7 +200,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -211,7 +211,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -222,7 +222,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -236,12 +236,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, KnowledgeBasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the knowledge bases client. + """Instantiates the knowledge bases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -296,9 +296,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -310,12 +311,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -330,8 +333,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -370,7 +373,6 @@ def list_knowledge_bases( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -402,10 +404,8 @@ def list_knowledge_bases( # there are no flattened fields. if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): request = knowledge_base.ListKnowledgeBasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -454,7 +454,6 @@ def get_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -493,10 +492,8 @@ def get_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): request = knowledge_base.GetKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -547,7 +544,6 @@ def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -586,10 +582,8 @@ def create_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -634,7 +628,6 @@ def delete_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -657,10 +650,8 @@ def delete_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): request = knowledge_base.DeleteKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -684,7 +675,7 @@ def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -710,7 +701,6 @@ def update_knowledge_base( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -749,10 +739,8 @@ def update_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py b/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py index 6939025df..b8b845661 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py index a3ac400b0..38da4326d 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py index 8173590b5..cb9322aca 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class KnowledgeBasesTransport(abc.ABC): """Abstract transport class for KnowledgeBases.""" @@ -48,21 +58,24 @@ class KnowledgeBasesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -139,11 +199,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_knowledge_bases( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.ListKnowledgeBasesRequest], - typing.Union[ + Union[ knowledge_base.ListKnowledgeBasesResponse, - typing.Awaitable[knowledge_base.ListKnowledgeBasesResponse], + Awaitable[knowledge_base.ListKnowledgeBasesResponse], ], ]: raise NotImplementedError() @@ -151,22 +211,20 @@ def list_knowledge_bases( @property def get_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.GetKnowledgeBaseRequest], - typing.Union[ - knowledge_base.KnowledgeBase, typing.Awaitable[knowledge_base.KnowledgeBase] - ], + Union[knowledge_base.KnowledgeBase, Awaitable[knowledge_base.KnowledgeBase]], ]: raise NotImplementedError() @property def create_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.CreateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() @@ -174,20 +232,20 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.DeleteKnowledgeBaseRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def update_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py index dd1f16ca4..3aa6b1f7c 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -314,7 +314,7 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty.Empty]: + ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty_pb2.Empty]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -333,7 +333,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py index f8372de6a..5bc13c924 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .grpc import KnowledgeBasesGrpcTransport @@ -56,7 +53,7 @@ class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -319,7 +318,9 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -338,7 +339,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2/services/participants/__init__.py b/google/cloud/dialogflow_v2/services/participants/__init__.py index 9ebfb1f70..942327781 100644 --- a/google/cloud/dialogflow_v2/services/participants/__init__.py +++ b/google/cloud/dialogflow_v2/services/participants/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ParticipantsClient from .async_client import ParticipantsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/participants/async_client.py b/google/cloud/dialogflow_v2/services/participants/async_client.py index beba5d8c1..ff13a6d05 100644 --- a/google/cloud/dialogflow_v2/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.participants import pagers from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant from google.cloud.dialogflow_v2.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport from .client import ParticipantsClient @@ -61,27 +58,22 @@ class ParticipantsAsyncClient: parse_session_entity_type_path = staticmethod( ParticipantsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( ParticipantsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ParticipantsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ParticipantsClient.common_folder_path) parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) - common_organization_path = staticmethod(ParticipantsClient.common_organization_path) parse_common_organization_path = staticmethod( ParticipantsClient.parse_common_organization_path ) - common_project_path = staticmethod(ParticipantsClient.common_project_path) parse_common_project_path = staticmethod( ParticipantsClient.parse_common_project_path ) - common_location_path = staticmethod(ParticipantsClient.common_location_path) parse_common_location_path = staticmethod( ParticipantsClient.parse_common_location_path @@ -89,7 +81,8 @@ class ParticipantsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ParticipantsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ParticipantsTransport: The transport used by the client instance. @@ -135,12 +128,12 @@ def transport(self) -> ParticipantsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ParticipantsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the participants client. + """Instantiates the participants client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -172,7 +165,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ParticipantsClient( credentials=credentials, transport=transport, @@ -209,7 +201,6 @@ async def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +227,6 @@ async def create_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -284,7 +274,6 @@ async def get_participant( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -311,7 +300,6 @@ async def get_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -359,7 +347,6 @@ async def list_participants( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -389,7 +376,6 @@ async def list_participants( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -424,7 +410,7 @@ async def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -447,7 +433,6 @@ async def update_participant( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -474,7 +459,6 @@ async def update_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -544,7 +528,6 @@ async def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -571,7 +554,6 @@ async def analyze_content( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -587,7 +569,9 @@ async def analyze_content( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -632,7 +616,6 @@ async def suggest_articles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -659,7 +642,6 @@ async def suggest_articles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -707,7 +689,6 @@ async def suggest_faq_answers( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -734,7 +715,6 @@ async def suggest_faq_answers( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/participants/client.py b/google/cloud/dialogflow_v2/services/participants/client.py index 9500f818f..466c36267 100644 --- a/google/cloud/dialogflow_v2/services/participants/client.py +++ b/google/cloud/dialogflow_v2/services/participants/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant from google.cloud.dialogflow_v2.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ParticipantsGrpcTransport from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ParticipantsClientMeta(type): _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ParticipantsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ParticipantsClient(metaclass=ParticipantsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ParticipantsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ParticipantsTransport: The transport used by the client instance. + ParticipantsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -176,27 +176,27 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified message string.""" + """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]: - """Parse a message path into its component segments.""" + """Parses a message path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path, @@ -205,14 +205,14 @@ def parse_message_path(path: str) -> Dict[str, str]: @staticmethod def participant_path(project: str, conversation: str, participant: str,) -> str: - """Return a fully-qualified participant string.""" + """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]: - """Parse a participant path into its component segments.""" + """Parses a participant path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path, @@ -221,14 +221,14 @@ def parse_participant_path(path: str) -> Dict[str, str]: @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -237,7 +237,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -250,7 +250,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -261,7 +261,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -272,7 +272,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -283,7 +283,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -297,12 +297,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ParticipantsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the participants client. + """Instantiates the participants client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -357,9 +357,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -371,12 +372,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -391,8 +394,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -436,7 +439,6 @@ def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -465,10 +467,8 @@ def create_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.CreateParticipantRequest): request = gcd_participant.CreateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -512,7 +512,6 @@ def get_participant( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -541,10 +540,8 @@ def get_participant( # there are no flattened fields. if not isinstance(request, participant.GetParticipantRequest): request = participant.GetParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -588,7 +585,6 @@ def list_participants( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -620,10 +616,8 @@ def list_participants( # there are no flattened fields. if not isinstance(request, participant.ListParticipantsRequest): request = participant.ListParticipantsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -654,7 +648,7 @@ def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -677,7 +671,6 @@ def update_participant( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -706,10 +699,8 @@ def update_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.UpdateParticipantRequest): request = gcd_participant.UpdateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -775,7 +766,6 @@ def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -804,10 +794,8 @@ def analyze_content( # there are no flattened fields. if not isinstance(request, gcd_participant.AnalyzeContentRequest): request = gcd_participant.AnalyzeContentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -857,7 +845,6 @@ def suggest_articles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -886,10 +873,8 @@ def suggest_articles( # there are no flattened fields. if not isinstance(request, participant.SuggestArticlesRequest): request = participant.SuggestArticlesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -933,7 +918,6 @@ def suggest_faq_answers( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -962,10 +946,8 @@ def suggest_faq_answers( # there are no flattened fields. if not isinstance(request, participant.SuggestFaqAnswersRequest): request = participant.SuggestFaqAnswersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/participants/pagers.py b/google/cloud/dialogflow_v2/services/participants/pagers.py index 48ce3c8ac..311970137 100644 --- a/google/cloud/dialogflow_v2/services/participants/pagers.py +++ b/google/cloud/dialogflow_v2/services/participants/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/participants/transports/__init__.py b/google/cloud/dialogflow_v2/services/participants/transports/__init__.py index 91a4cec1c..522813c1c 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/participants/transports/base.py b/google/cloud/dialogflow_v2/services/participants/transports/base.py index 357674581..62cbe33a9 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ParticipantsTransport(abc.ABC): """Abstract transport class for Participants.""" @@ -47,21 +57,24 @@ class ParticipantsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -128,7 +188,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -145,33 +207,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.CreateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def get_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.GetParticipantRequest], - typing.Union[ - participant.Participant, typing.Awaitable[participant.Participant] - ], + Union[participant.Participant, Awaitable[participant.Participant]], ]: raise NotImplementedError() @property def list_participants( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListParticipantsRequest], - typing.Union[ + Union[ participant.ListParticipantsResponse, - typing.Awaitable[participant.ListParticipantsResponse], + Awaitable[participant.ListParticipantsResponse], ], ]: raise NotImplementedError() @@ -179,22 +237,20 @@ def list_participants( @property def update_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.UpdateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def analyze_content( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.AnalyzeContentRequest], - typing.Union[ + Union[ gcd_participant.AnalyzeContentResponse, - typing.Awaitable[gcd_participant.AnalyzeContentResponse], + Awaitable[gcd_participant.AnalyzeContentResponse], ], ]: raise NotImplementedError() @@ -202,11 +258,11 @@ def analyze_content( @property def suggest_articles( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestArticlesRequest], - typing.Union[ + Union[ participant.SuggestArticlesResponse, - typing.Awaitable[participant.SuggestArticlesResponse], + Awaitable[participant.SuggestArticlesResponse], ], ]: raise NotImplementedError() @@ -214,11 +270,11 @@ def suggest_articles( @property def suggest_faq_answers( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestFaqAnswersRequest], - typing.Union[ + Union[ participant.SuggestFaqAnswersResponse, - typing.Awaitable[participant.SuggestFaqAnswersResponse], + Awaitable[participant.SuggestFaqAnswersResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc.py index e4543e6bf..51b06e9a3 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py index 78dc60b4b..138d07b2b 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .grpc import ParticipantsGrpcTransport @@ -55,7 +52,7 @@ class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py b/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py index c0dca267f..cbd406b49 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionEntityTypesClient from .async_client import SessionEntityTypesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py b/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py index 0eb8e3f7c..738a174d3 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport from .client import SessionEntityTypesClient @@ -57,31 +54,26 @@ class SessionEntityTypesAsyncClient: parse_session_entity_type_path = staticmethod( SessionEntityTypesClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionEntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionEntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod( SessionEntityTypesClient.parse_common_folder_path ) - common_organization_path = staticmethod( SessionEntityTypesClient.common_organization_path ) parse_common_organization_path = staticmethod( SessionEntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) parse_common_project_path = staticmethod( SessionEntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) parse_common_location_path = staticmethod( SessionEntityTypesClient.parse_common_location_path @@ -89,7 +81,8 @@ class SessionEntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionEntityTypesTransport: The transport used by the client instance. @@ -136,12 +129,12 @@ def transport(self) -> SessionEntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -173,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -212,7 +204,6 @@ async def list_session_entity_types( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -242,7 +233,6 @@ async def list_session_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -302,7 +292,6 @@ async def get_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -337,7 +326,6 @@ async def get_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -402,7 +390,6 @@ async def create_session_entity_type( This corresponds to the ``session_entity_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -437,7 +424,6 @@ async def create_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -468,7 +454,7 @@ async def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -496,7 +482,6 @@ async def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -531,7 +516,6 @@ async def update_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -589,7 +573,6 @@ async def delete_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -610,7 +593,6 @@ async def delete_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/client.py b/google/cloud/dialogflow_v2/services/session_entity_types/client.py index 01c08eba2..60cbbf143 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/client.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,8 +36,7 @@ from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionEntityTypesGrpcTransport from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class SessionEntityTypesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SessionEntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,23 +156,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionEntityTypesTransport: The transport used by the client instance. + SessionEntityTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -182,7 +182,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -195,7 +195,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -206,7 +206,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -242,12 +242,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionEntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -302,9 +302,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -316,12 +317,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -336,8 +339,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -383,7 +386,6 @@ def list_session_entity_types( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -415,10 +417,8 @@ def list_session_entity_types( # there are no flattened fields. if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): request = session_entity_type.ListSessionEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -476,7 +476,6 @@ def get_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -513,10 +512,8 @@ def get_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): request = session_entity_type.GetSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -577,7 +574,6 @@ def create_session_entity_type( This corresponds to the ``session_entity_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -616,10 +612,8 @@ def create_session_entity_type( request, gcd_session_entity_type.CreateSessionEntityTypeRequest ): request = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -648,7 +642,7 @@ def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -676,7 +670,6 @@ def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -715,10 +708,8 @@ def update_session_entity_type( request, gcd_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -774,7 +765,6 @@ def delete_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -797,10 +787,8 @@ def delete_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): request = session_entity_type.DeleteSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py b/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py index 3242ab3e7..a3b58bcf5 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py index 606f91160..633fd32cb 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py index 529860533..69ce0f2cd 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import session_entity_type from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -50,21 +60,24 @@ class SessionEntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_session_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.ListSessionEntityTypesRequest], - typing.Union[ + Union[ session_entity_type.ListSessionEntityTypesResponse, - typing.Awaitable[session_entity_type.ListSessionEntityTypesResponse], + Awaitable[session_entity_type.ListSessionEntityTypesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_session_entity_types( @property def get_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.GetSessionEntityTypeRequest], - typing.Union[ + Union[ session_entity_type.SessionEntityType, - typing.Awaitable[session_entity_type.SessionEntityType], + Awaitable[session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_session_entity_type( @property def create_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_session_entity_type( @property def update_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.DeleteSessionEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py index d68070365..9b01b6dd0 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,8 +28,7 @@ from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -361,7 +361,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> Callable[[session_entity_type.DeleteSessionEntityTypeRequest], empty.Empty]: + ) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete session entity type method over gRPC. Deletes the specified session entity type. @@ -383,7 +385,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py index feaffcd71..ed5ff7cca 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,8 +29,7 @@ from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import SessionEntityTypesGrpcTransport @@ -58,7 +55,7 @@ class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -366,7 +365,7 @@ def update_session_entity_type( def delete_session_entity_type( self, ) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty.Empty] + [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete session entity type method over gRPC. @@ -389,7 +388,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflow_v2/services/sessions/__init__.py b/google/cloud/dialogflow_v2/services/sessions/__init__.py index 3b2a59a9d..0adeafb97 100644 --- a/google/cloud/dialogflow_v2/services/sessions/__init__.py +++ b/google/cloud/dialogflow_v2/services/sessions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionsClient from .async_client import SessionsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/sessions/async_client.py b/google/cloud/dialogflow_v2/services/sessions/async_client.py index e479f1bce..dd5dca4cd 100644 --- a/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2/services/sessions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,17 +29,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -69,31 +66,27 @@ class SessionsAsyncClient: parse_session_entity_type_path = staticmethod( SessionsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionsClient.common_folder_path) parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) parse_common_organization_path = staticmethod( SessionsClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionsClient.common_project_path) parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -108,7 +101,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -125,7 +118,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionsTransport: The transport used by the client instance. @@ -139,12 +132,12 @@ def transport(self) -> SessionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -176,7 +169,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -247,7 +239,6 @@ async def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -274,7 +265,6 @@ async def detect_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: @@ -288,7 +278,9 @@ async def detect_intent( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, diff --git a/google/cloud/dialogflow_v2/services/sessions/client.py b/google/cloud/dialogflow_v2/services/sessions/client.py index f601843e0..3ca585180 100644 --- a/google/cloud/dialogflow_v2/services/sessions/client.py +++ b/google/cloud/dialogflow_v2/services/sessions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -45,8 +43,7 @@ from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -65,7 +62,7 @@ class SessionsClientMeta(type): _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SessionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -92,7 +89,8 @@ class SessionsClient(metaclass=SessionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -126,7 +124,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -143,7 +142,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -162,23 +161,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionsTransport: The transport used by the client instance. + SessionsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -187,27 +187,27 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified session string.""" + """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]: - """Parse a session path into its component segments.""" + """Parses a session path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path ) @@ -215,14 +215,14 @@ def parse_session_path(path: str) -> Dict[str, str]: @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -231,7 +231,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -244,7 +244,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -255,7 +255,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -266,7 +266,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -277,7 +277,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -291,12 +291,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -351,9 +351,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -365,12 +366,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -385,8 +388,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -464,7 +467,6 @@ def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -493,10 +495,8 @@ def detect_intent( # there are no flattened fields. if not isinstance(request, gcd_session.DetectIntentRequest): request = gcd_session.DetectIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py b/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py index 0ca6c76ea..db0f7d045 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/base.py b/google/cloud/dialogflow_v2/services/sessions/transports/base.py index 4441c222d..fd9173f8a 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -47,21 +57,24 @@ class SessionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -132,11 +194,11 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session.DetectIntentRequest], - typing.Union[ + Union[ gcd_session.DetectIntentResponse, - typing.Awaitable[gcd_session.DetectIntentResponse], + Awaitable[gcd_session.DetectIntentResponse], ], ]: raise NotImplementedError() @@ -144,11 +206,11 @@ def detect_intent( @property def streaming_detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.StreamingDetectIntentRequest], - typing.Union[ + Union[ session.StreamingDetectIntentResponse, - typing.Awaitable[session.StreamingDetectIntentResponse], + Awaitable[session.StreamingDetectIntentResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py index 995202acf..f497eb6e5 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py index 69689dd2a..f3128aae5 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -57,7 +54,7 @@ class SessionsGrpcAsyncIOTransport(SessionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py b/google/cloud/dialogflow_v2/services/versions/__init__.py similarity index 93% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py rename to google/cloud/dialogflow_v2/services/versions/__init__.py index 630246bde..586be1818 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py +++ b/google/cloud/dialogflow_v2/services/versions/__init__.py @@ -17,6 +17,6 @@ from .async_client import VersionsAsyncClient __all__ = ( - 'VersionsClient', - 'VersionsAsyncClient', + "VersionsClient", + "VersionsAsyncClient", ) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py b/google/cloud/dialogflow_v2/services/versions/async_client.py similarity index 81% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py rename to google/cloud/dialogflow_v2/services/versions/async_client.py index 68b1a8aea..395c6b0d4 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py +++ b/google/cloud/dialogflow_v2/services/versions/async_client.py @@ -19,12 +19,12 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.versions import pagers from google.cloud.dialogflow_v2.types import version @@ -46,12 +46,18 @@ class VersionsAsyncClient: version_path = staticmethod(VersionsClient.version_path) parse_version_path = staticmethod(VersionsClient.parse_version_path) - common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_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) + 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) @@ -99,14 +105,18 @@ def transport(self) -> VersionsTransport: """ return self._client.transport - get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + get_transport_class = functools.partial( + type(VersionsClient).get_transport_class, type(VersionsClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VersionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the versions client. Args: @@ -144,17 +154,17 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def list_versions(self, - request: version.ListVersionsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsAsyncPager: + async def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: r"""Returns the list of all versions of the specified agent. @@ -192,8 +202,10 @@ async def list_versions(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.ListVersionsRequest(request) @@ -213,39 +225,30 @@ async def list_versions(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + 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, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - async def get_version(self, - request: version.GetVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: + async def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: r"""Retrieves the specified agent version. Args: @@ -297,8 +300,10 @@ async def get_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.GetVersionRequest(request) @@ -318,31 +323,25 @@ async def get_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def create_version(self, - request: gcd_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcd_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + async def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Creates an agent version. The new version points to the agent instance in the "default" environment. @@ -402,8 +401,10 @@ async def create_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_version.CreateVersionRequest(request) @@ -425,31 +426,25 @@ async def create_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def update_version(self, - request: gcd_version.UpdateVersionRequest = None, - *, - version: gcd_version.Version = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + async def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Updates the specified agent version. Note that this method does not allow you to update the state of the agent the given version points to. It @@ -512,8 +507,10 @@ async def update_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_version.UpdateVersionRequest(request) @@ -535,30 +532,26 @@ async def update_version(self, # 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), - )), + 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, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def delete_version(self, - request: version.DeleteVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: + async def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: r"""Delete the specified agent version. Args: @@ -586,8 +579,10 @@ async def delete_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.DeleteVersionRequest(request) @@ -607,23 +602,15 @@ async def delete_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, + request, retry=retry, timeout=timeout, metadata=metadata, ) - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -634,6 +621,4 @@ async def delete_version(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "VersionsAsyncClient", -) +__all__ = ("VersionsAsyncClient",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py b/google/cloud/dialogflow_v2/services/versions/client.py similarity index 82% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py rename to google/cloud/dialogflow_v2/services/versions/client.py index ff73df380..b0c30ea34 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py +++ b/google/cloud/dialogflow_v2/services/versions/client.py @@ -21,14 +21,14 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2.services.versions import pagers from google.cloud.dialogflow_v2.types import version @@ -47,13 +47,12 @@ class VersionsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] _transport_registry["grpc"] = VersionsGrpcTransport _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[VersionsTransport]: + def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: """Returns an appropriate transport class. Args: @@ -141,8 +140,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: VersionsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -159,77 +157,87 @@ def transport(self) -> VersionsTransport: return self._transport @staticmethod - def version_path(project: str,version: str,) -> str: + 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, ) + return "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: + 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) + 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: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format(folder=folder,) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format(organization=organization,) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format(project=project,) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VersionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the versions client. Args: @@ -273,7 +281,9 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) client_cert_source_func = None is_mtls = False @@ -314,8 +324,10 @@ def __init__(self, *, if isinstance(transport, VersionsTransport): # transport is a VersionsTransport instance. if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -334,14 +346,15 @@ def __init__(self, *, client_info=client_info, ) - def list_versions(self, - request: version.ListVersionsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsPager: + def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: r"""Returns the list of all versions of the specified agent. @@ -379,8 +392,10 @@ def list_versions(self, # 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.') + 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. @@ -400,39 +415,30 @@ def list_versions(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + 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, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - def get_version(self, - request: version.GetVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: + def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: r"""Retrieves the specified agent version. Args: @@ -484,8 +490,10 @@ def get_version(self, # 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.') + 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. @@ -505,31 +513,25 @@ def get_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def create_version(self, - request: gcd_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcd_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Creates an agent version. The new version points to the agent instance in the "default" environment. @@ -589,8 +591,10 @@ def create_version(self, # 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.') + 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. @@ -612,31 +616,25 @@ def create_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def update_version(self, - request: gcd_version.UpdateVersionRequest = None, - *, - version: gcd_version.Version = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Updates the specified agent version. Note that this method does not allow you to update the state of the agent the given version points to. It @@ -699,8 +697,10 @@ def update_version(self, # 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.') + 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. @@ -722,30 +722,26 @@ def update_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("version.name", request.version.name),) + ), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def delete_version(self, - request: version.DeleteVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: + def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: r"""Delete the specified agent version. Args: @@ -773,8 +769,10 @@ def delete_version(self, # 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.') + 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. @@ -794,23 +792,15 @@ def delete_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, + request, retry=retry, timeout=timeout, metadata=metadata, ) - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -821,6 +811,4 @@ def delete_version(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "VersionsClient", -) +__all__ = ("VersionsClient",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py b/google/cloud/dialogflow_v2/services/versions/pagers.py similarity index 86% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py rename to google/cloud/dialogflow_v2/services/versions/pagers.py index bead6290c..316090b46 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py +++ b/google/cloud/dialogflow_v2/services/versions/pagers.py @@ -13,7 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) from google.cloud.dialogflow_v2.types import version @@ -35,12 +44,15 @@ class ListVersionsPager: 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]] = ()): + + def __init__( + self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -74,7 +86,7 @@ def __iter__(self) -> Iterable[version.Version]: yield from page.versions def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListVersionsAsyncPager: @@ -94,12 +106,15 @@ class ListVersionsAsyncPager: 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]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -137,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + 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/google/cloud/dialogflow_v2/services/versions/transports/__init__.py similarity index 81% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py rename to google/cloud/dialogflow_v2/services/versions/transports/__init__.py index dfb70ce95..c5a42a0e8 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/versions/transports/__init__.py @@ -23,11 +23,11 @@ # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] -_transport_registry['grpc'] = VersionsGrpcTransport -_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport +_transport_registry["grpc"] = VersionsGrpcTransport +_transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport __all__ = ( - 'VersionsTransport', - 'VersionsGrpcTransport', - 'VersionsGrpcAsyncIOTransport', + "VersionsTransport", + "VersionsGrpcTransport", + "VersionsGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py b/google/cloud/dialogflow_v2/services/versions/transports/base.py similarity index 67% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py rename to google/cloud/dialogflow_v2/services/versions/transports/base.py index 8e207d9aa..2ff8e9d06 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py +++ b/google/cloud/dialogflow_v2/services/versions/transports/base.py @@ -21,7 +21,7 @@ import google.auth # type: ignore import google.api_core # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -32,7 +32,7 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', + "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: @@ -54,21 +54,23 @@ class VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ) - DEFAULT_HOST: str = 'dialogflow.googleapis.com' + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -92,8 +94,8 @@ def __init__( your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) @@ -104,17 +106,19 @@ def __init__( # 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") + 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 - ) + 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) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials @@ -126,7 +130,9 @@ def __init__( # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" scopes_kwargs = {} @@ -143,7 +149,9 @@ def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[ # TODO: Remove this function once google-api-core >= 1.26.0 is required @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} @@ -164,78 +172,65 @@ 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.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.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.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.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, + self.delete_version, default_timeout=None, client_info=client_info, ), - } + } @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - Union[ - version.ListVersionsResponse, - Awaitable[version.ListVersionsResponse] - ]]: + 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] - ]]: + 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] - ]]: + 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] - ]]: + 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] - ]]: + def delete_version( + self, + ) -> Callable[ + [version.DeleteVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() -__all__ = ( - 'VersionsTransport', -) +__all__ = ("VersionsTransport",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py b/google/cloud/dialogflow_v2/services/versions/transports/grpc.py similarity index 80% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py rename to google/cloud/dialogflow_v2/services/versions/transports/grpc.py index 5294fdbd8..517e8196a 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/versions/transports/grpc.py @@ -16,9 +16,9 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -42,21 +42,24 @@ class VersionsGrpcTransport(VersionsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -168,13 +171,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -209,7 +214,7 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) @property @@ -219,9 +224,9 @@ def grpc_channel(self) -> grpc.Channel: return self._grpc_channel @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: + 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 @@ -237,18 +242,16 @@ def list_versions(self) -> Callable[ # 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', + 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'] + return self._stubs["list_versions"] @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - version.Version]: + 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. @@ -263,18 +266,18 @@ def get_version(self) -> Callable[ # 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', + 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'] + return self._stubs["get_version"] @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - gcd_version.Version]: + 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. @@ -291,18 +294,18 @@ def create_version(self) -> Callable[ # 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', + 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'] + return self._stubs["create_version"] @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - gcd_version.Version]: + 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. @@ -321,18 +324,18 @@ def update_version(self) -> Callable[ # 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', + 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'] + return self._stubs["update_version"] @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - empty_pb2.Empty]: + 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. @@ -347,15 +350,13 @@ def delete_version(self) -> Callable[ # 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', + 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'] + return self._stubs["delete_version"] -__all__ = ( - 'VersionsGrpcTransport', -) +__all__ = ("VersionsGrpcTransport",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py similarity index 80% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py rename to google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py index 74847abc3..5efe9b1e8 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py @@ -16,13 +16,13 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version -import grpc # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2.types import version @@ -49,13 +49,15 @@ class VersionsGrpcAsyncIOTransport(VersionsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -86,22 +88,24 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -223,9 +227,11 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - Awaitable[version.ListVersionsResponse]]: + 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 @@ -241,18 +247,18 @@ def list_versions(self) -> Callable[ # 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', + 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'] + return self._stubs["list_versions"] @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - Awaitable[version.Version]]: + 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. @@ -267,18 +273,18 @@ def get_version(self) -> Callable[ # 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', + 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'] + return self._stubs["get_version"] @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - Awaitable[gcd_version.Version]]: + 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. @@ -295,18 +301,18 @@ def create_version(self) -> Callable[ # 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', + 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'] + return self._stubs["create_version"] @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - Awaitable[gcd_version.Version]]: + 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. @@ -325,18 +331,18 @@ def update_version(self) -> Callable[ # 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', + 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'] + return self._stubs["update_version"] @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - Awaitable[empty_pb2.Empty]]: + 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. @@ -351,15 +357,13 @@ def delete_version(self) -> Callable[ # 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', + 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'] + return self._stubs["delete_version"] -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) +__all__ = ("VersionsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2/types/__init__.py b/google/cloud/dialogflow_v2/types/__init__.py index ba48aa9da..7426db72a 100644 --- a/google/cloud/dialogflow_v2/types/__init__.py +++ b/google/cloud/dialogflow_v2/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .agent import ( Agent, DeleteAgentRequest, @@ -116,9 +114,21 @@ UpdateEntityTypeRequest, ) from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, ListEnvironmentsRequest, ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, ) from .human_agent_assistant_event import HumanAgentAssistantEvent from .intent import ( @@ -195,6 +205,15 @@ ValidationError, ValidationResult, ) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) from .webhook import ( OriginalDetectIntentRequest, WebhookRequest, @@ -286,9 +305,19 @@ "ListEntityTypesRequest", "ListEntityTypesResponse", "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", "HumanAgentAssistantEvent", "BatchDeleteIntentsRequest", "BatchUpdateIntentsRequest", @@ -352,6 +381,13 @@ "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", diff --git a/google/cloud/dialogflow_v2/types/agent.py b/google/cloud/dialogflow_v2/types/agent.py index 9309c84bc..7cee91fec 100644 --- a/google/cloud/dialogflow_v2/types/agent.py +++ b/google/cloud/dialogflow_v2/types/agent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -133,28 +130,17 @@ class Tier(proto.Enum): TIER_ENTERPRISE = 2 TIER_ENTERPRISE_PLUS = 3 - parent = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - default_language_code = proto.Field(proto.STRING, number=3) - - supported_language_codes = proto.RepeatedField(proto.STRING, number=4) - - time_zone = proto.Field(proto.STRING, number=5) - - description = proto.Field(proto.STRING, number=6) - - avatar_uri = proto.Field(proto.STRING, number=7) - - enable_logging = proto.Field(proto.BOOL, number=8) - + parent = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + default_language_code = proto.Field(proto.STRING, number=3,) + supported_language_codes = proto.RepeatedField(proto.STRING, number=4,) + time_zone = proto.Field(proto.STRING, number=5,) + description = proto.Field(proto.STRING, number=6,) + avatar_uri = proto.Field(proto.STRING, number=7,) + enable_logging = proto.Field(proto.BOOL, number=8,) match_mode = proto.Field(proto.ENUM, number=9, enum=MatchMode,) - - classification_threshold = proto.Field(proto.FLOAT, number=10) - + classification_threshold = proto.Field(proto.FLOAT, number=10,) api_version = proto.Field(proto.ENUM, number=14, enum=ApiVersion,) - tier = proto.Field(proto.ENUM, number=15, enum=Tier,) @@ -168,7 +154,7 @@ class GetAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SetAgentRequest(proto.Message): @@ -184,8 +170,9 @@ class SetAgentRequest(proto.Message): """ agent = proto.Field(proto.MESSAGE, number=1, message="Agent",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteAgentRequest(proto.Message): @@ -198,7 +185,7 @@ class DeleteAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SearchAgentsRequest(proto.Message): @@ -218,11 +205,9 @@ class SearchAgentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class SearchAgentsResponse(proto.Message): @@ -244,8 +229,7 @@ def raw_page(self): return self agents = proto.RepeatedField(proto.MESSAGE, number=1, message="Agent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class TrainAgentRequest(proto.Message): @@ -258,7 +242,7 @@ class TrainAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -277,9 +261,8 @@ class ExportAgentRequest(proto.Message): the serialized agent is returned inline. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) class ExportAgentResponse(proto.Message): @@ -295,9 +278,8 @@ class ExportAgentResponse(proto.Message): Zip compressed raw byte content for agent. """ - agent_uri = proto.Field(proto.STRING, number=1, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=2, oneof="agent") + agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=2, oneof="agent",) class ImportAgentRequest(proto.Message): @@ -316,11 +298,9 @@ class ImportAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) class RestoreAgentRequest(proto.Message): @@ -339,11 +319,9 @@ class RestoreAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) class GetValidationResultRequest(proto.Message): @@ -363,9 +341,8 @@ class GetValidationResultRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/answer_record.py b/google/cloud/dialogflow_v2/types/answer_record.py index 57866e0e5..92a8accd9 100644 --- a/google/cloud/dialogflow_v2/types/answer_record.py +++ b/google/cloud/dialogflow_v2/types/answer_record.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import participant -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -81,10 +78,8 @@ class AnswerRecord(proto.Message): assistant. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) answer_feedback = proto.Field(proto.MESSAGE, number=2, message="AnswerFeedback",) - agent_assistant_record = proto.Field( proto.MESSAGE, number=4, oneof="record", message="AgentAssistantRecord", ) @@ -119,13 +114,10 @@ class ListAnswerRecordsRequest(proto.Message): listing on the next page. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListAnswerRecordsResponse(proto.Message): @@ -150,8 +142,7 @@ def raw_page(self): answer_records = proto.RepeatedField( proto.MESSAGE, number=1, message="AnswerRecord", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateAnswerRecordRequest(proto.Message): @@ -167,8 +158,9 @@ class UpdateAnswerRecordRequest(proto.Message): """ answer_record = proto.Field(proto.MESSAGE, number=1, message="AnswerRecord",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class AnswerFeedback(proto.Message): @@ -201,26 +193,22 @@ class CorrectnessLevel(proto.Enum): FULLY_CORRECT = 3 correctness_level = proto.Field(proto.ENUM, number=1, enum=CorrectnessLevel,) - agent_assistant_detail_feedback = proto.Field( proto.MESSAGE, number=2, oneof="detail_feedback", message="AgentAssistantFeedback", ) - - clicked = proto.Field(proto.BOOL, number=3) - - click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - displayed = proto.Field(proto.BOOL, number=4) - - display_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + clicked = proto.Field(proto.BOOL, number=3,) + click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + displayed = proto.Field(proto.BOOL, number=4,) + display_time = proto.Field( + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, + ) class AgentAssistantFeedback(proto.Message): r"""Detail feedback of Agent Assist result. - Attributes: answer_relevance (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.AnswerRelevance): Optional. Whether or not the suggested answer is relevant. @@ -273,15 +261,12 @@ class DocumentEfficiency(proto.Enum): EFFICIENT = 2 answer_relevance = proto.Field(proto.ENUM, number=1, enum=AnswerRelevance,) - document_correctness = proto.Field(proto.ENUM, number=2, enum=DocumentCorrectness,) - document_efficiency = proto.Field(proto.ENUM, number=3, enum=DocumentEfficiency,) class AgentAssistantRecord(proto.Message): r"""Represents a record of a human agent assist answer. - Attributes: article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): Output only. The article suggestion answer. @@ -292,7 +277,6 @@ class AgentAssistantRecord(proto.Message): article_suggestion_answer = proto.Field( proto.MESSAGE, number=5, oneof="answer", message=participant.ArticleAnswer, ) - faq_answer = proto.Field( proto.MESSAGE, number=6, oneof="answer", message=participant.FaqAnswer, ) diff --git a/google/cloud/dialogflow_v2/types/audio_config.py b/google/cloud/dialogflow_v2/types/audio_config.py index 4b8ecf6d8..5cca3a22f 100644 --- a/google/cloud/dialogflow_v2/types/audio_config.py +++ b/google/cloud/dialogflow_v2/types/audio_config.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -127,14 +124,12 @@ class SpeechContext(proto.Message): binary search. """ - phrases = proto.RepeatedField(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=2) + phrases = proto.RepeatedField(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=2,) class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -161,13 +156,10 @@ class SpeechWordInfo(proto.Message): also not rely on it to always be provided. """ - word = proto.Field(proto.STRING, number=3) - - start_offset = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_offset = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - confidence = proto.Field(proto.FLOAT, number=4) + word = proto.Field(proto.STRING, number=3,) + start_offset = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_offset = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + confidence = proto.Field(proto.FLOAT, number=4,) class InputAudioConfig(proto.Message): @@ -254,31 +246,21 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) speech_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message="SpeechContext", ) - - model = proto.Field(proto.STRING, number=7) - + model = proto.Field(proto.STRING, number=7,) model_variant = proto.Field(proto.ENUM, number=10, enum="SpeechModelVariant",) - - single_utterance = proto.Field(proto.BOOL, number=8) - - disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14) + single_utterance = proto.Field(proto.BOOL, number=8,) + disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14,) class VoiceSelectionParams(proto.Message): r"""Description of which voice to use for speech synthesis. - Attributes: name (str): Optional. The name of the voice. If not set, the service @@ -296,14 +278,12 @@ class VoiceSelectionParams(proto.Message): gender rather than failing the request. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) ssml_gender = proto.Field(proto.ENUM, number=2, enum="SsmlVoiceGender",) class SynthesizeSpeechConfig(proto.Message): r"""Configuration of how speech should be synthesized. - Attributes: speaking_rate (float): Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 @@ -337,14 +317,10 @@ class SynthesizeSpeechConfig(proto.Message): synthesized audio. """ - speaking_rate = proto.Field(proto.DOUBLE, number=1) - - pitch = proto.Field(proto.DOUBLE, number=2) - - volume_gain_db = proto.Field(proto.DOUBLE, number=3) - - effects_profile_id = proto.RepeatedField(proto.STRING, number=5) - + speaking_rate = proto.Field(proto.DOUBLE, number=1,) + pitch = proto.Field(proto.DOUBLE, number=2,) + volume_gain_db = proto.Field(proto.DOUBLE, number=3,) + effects_profile_id = proto.RepeatedField(proto.STRING, number=5,) voice = proto.Field(proto.MESSAGE, number=4, message="VoiceSelectionParams",) @@ -373,9 +349,7 @@ class OutputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="OutputAudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) synthesize_speech_config = proto.Field( proto.MESSAGE, number=3, message="SynthesizeSpeechConfig", ) diff --git a/google/cloud/dialogflow_v2/types/context.py b/google/cloud/dialogflow_v2/types/context.py index 72e6564de..0b16c4140 100644 --- a/google/cloud/dialogflow_v2/types/context.py +++ b/google/cloud/dialogflow_v2/types/context.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -105,11 +102,9 @@ class Context(proto.Message): Else: parameter value """ - name = proto.Field(proto.STRING, number=1) - - lifespan_count = proto.Field(proto.INT32, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + name = proto.Field(proto.STRING, number=1,) + lifespan_count = proto.Field(proto.INT32, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) class ListContextsRequest(proto.Message): @@ -133,11 +128,9 @@ class ListContextsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListContextsResponse(proto.Message): @@ -159,8 +152,7 @@ def raw_page(self): return self contexts = proto.RepeatedField(proto.MESSAGE, number=1, message="Context",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetContextRequest(proto.Message): @@ -178,7 +170,7 @@ class GetContextRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateContextRequest(proto.Message): @@ -197,8 +189,7 @@ class CreateContextRequest(proto.Message): Required. The context to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) context = proto.Field(proto.MESSAGE, number=2, message="Context",) @@ -215,8 +206,9 @@ class UpdateContextRequest(proto.Message): """ context = proto.Field(proto.MESSAGE, number=1, message="Context",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteContextRequest(proto.Message): @@ -234,7 +226,7 @@ class DeleteContextRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteAllContextsRequest(proto.Message): @@ -252,7 +244,7 @@ class DeleteAllContextsRequest(proto.Message): assume default '-' user. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/conversation.py b/google/cloud/dialogflow_v2/types/conversation.py index a53db5ebe..f6d392fef 100644 --- a/google/cloud/dialogflow_v2/types/conversation.py +++ b/google/cloud/dialogflow_v2/types/conversation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -102,20 +99,14 @@ class ConversationStage(proto.Enum): VIRTUAL_AGENT_STAGE = 1 HUMAN_ASSIST_STAGE = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) lifecycle_state = proto.Field(proto.ENUM, number=2, enum=LifecycleState,) - - conversation_profile = proto.Field(proto.STRING, number=3) - + conversation_profile = proto.Field(proto.STRING, number=3,) phone_number = proto.Field( proto.MESSAGE, number=4, message="ConversationPhoneNumber", ) - - start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) conversation_stage = proto.Field(proto.ENUM, number=7, enum=ConversationStage,) @@ -146,11 +137,9 @@ class CreateConversationRequest(proto.Message): a project to better ensure uniqueness. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation = proto.Field(proto.MESSAGE, number=2, message="Conversation",) - - conversation_id = proto.Field(proto.STRING, number=3) + conversation_id = proto.Field(proto.STRING, number=3,) class ListConversationsRequest(proto.Message): @@ -192,13 +181,10 @@ class ListConversationsRequest(proto.Message): Filtering `__. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListConversationsResponse(proto.Message): @@ -222,8 +208,7 @@ def raw_page(self): conversations = proto.RepeatedField( proto.MESSAGE, number=1, message="Conversation", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationRequest(proto.Message): @@ -236,7 +221,7 @@ class GetConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CompleteConversationRequest(proto.Message): @@ -250,7 +235,7 @@ class CompleteConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListMessagesRequest(proto.Message): @@ -281,13 +266,10 @@ class ListMessagesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListMessagesResponse(proto.Message): @@ -313,8 +295,7 @@ def raw_page(self): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=participant.Message, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ConversationPhoneNumber(proto.Message): @@ -327,7 +308,7 @@ class ConversationPhoneNumber(proto.Message): this conversation. """ - phone_number = proto.Field(proto.STRING, number=3) + phone_number = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/conversation_event.py b/google/cloud/dialogflow_v2/types/conversation_event.py index 1f6551e7a..193259b4f 100644 --- a/google/cloud/dialogflow_v2/types/conversation_event.py +++ b/google/cloud/dialogflow_v2/types/conversation_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import participant -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -55,12 +52,9 @@ class Type(proto.Enum): NEW_MESSAGE = 5 UNRECOVERABLE_ERROR = 4 - conversation = proto.Field(proto.STRING, number=1) - + conversation = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - error_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - + error_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) new_message_payload = proto.Field( proto.MESSAGE, number=4, oneof="payload", message=participant.Message, ) diff --git a/google/cloud/dialogflow_v2/types/conversation_profile.py b/google/cloud/dialogflow_v2/types/conversation_profile.py index c792728dd..b7022be1b 100644 --- a/google/cloud/dialogflow_v2/types/conversation_profile.py +++ b/google/cloud/dialogflow_v2/types/conversation_profile.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import audio_config -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -49,8 +46,7 @@ class ConversationProfile(proto.Message): Attributes: name (str): - Optional. The unique identifier of this conversation - profile. Format: + The unique identifier of this conversation profile. Format: ``projects//locations//conversationProfiles/``. display_name (str): Required. Human readable name for this @@ -69,6 +65,8 @@ class ConversationProfile(proto.Message): with this profile. human_agent_handoff_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig): Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): Configuration for publishing conversation lifecycle events. @@ -89,41 +87,34 @@ class ConversationProfile(proto.Message): they want to support. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - create_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=12, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=11, message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, number=12, message=timestamp_pb2.Timestamp, + ) automated_agent_config = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentConfig", ) - human_agent_assistant_config = proto.Field( proto.MESSAGE, number=4, message="HumanAgentAssistantConfig", ) - human_agent_handoff_config = proto.Field( proto.MESSAGE, number=5, message="HumanAgentHandoffConfig", ) - notification_config = proto.Field( proto.MESSAGE, number=6, message="NotificationConfig", ) - logging_config = proto.Field(proto.MESSAGE, number=7, message="LoggingConfig",) - new_message_event_notification_config = proto.Field( proto.MESSAGE, number=8, message="NotificationConfig", ) - stt_config = proto.Field( proto.MESSAGE, number=9, message=audio_config.SpeechToTextConfig, ) - - language_code = proto.Field(proto.STRING, number=10) + language_code = proto.Field(proto.STRING, number=10,) class ListConversationProfilesRequest(proto.Message): @@ -143,11 +134,9 @@ class ListConversationProfilesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListConversationProfilesResponse(proto.Message): @@ -172,8 +161,7 @@ def raw_page(self): conversation_profiles = proto.RepeatedField( proto.MESSAGE, number=1, message="ConversationProfile", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationProfileRequest(proto.Message): @@ -187,7 +175,7 @@ class GetConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateConversationProfileRequest(proto.Message): @@ -202,8 +190,7 @@ class CreateConversationProfileRequest(proto.Message): Required. The conversation profile to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation_profile = proto.Field( proto.MESSAGE, number=2, message="ConversationProfile", ) @@ -224,8 +211,9 @@ class UpdateConversationProfileRequest(proto.Message): conversation_profile = proto.Field( proto.MESSAGE, number=1, message="ConversationProfile", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteConversationProfileRequest(proto.Message): @@ -242,12 +230,11 @@ class DeleteConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class AutomatedAgentConfig(proto.Message): r"""Defines the Automated Agent to connect to a conversation. - Attributes: agent (str): Required. ID of the Dialogflow agent environment to use. @@ -265,12 +252,11 @@ class AutomatedAgentConfig(proto.Message): for more details. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class HumanAgentAssistantConfig(proto.Message): r"""Defines the Human Agent Assist to connect to a conversation. - Attributes: notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): Pub/Sub topic on which to publish new agent @@ -281,13 +267,14 @@ class HumanAgentAssistantConfig(proto.Message): end_user_suggestion_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionConfig): Configuration for agent assistance of end user participant. + Currently, this feature is not general + available, please contact Google to get access. message_analysis_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.MessageAnalysisConfig): Configuration for message analysis. """ class SuggestionTriggerSettings(proto.Message): r"""Settings of suggestion trigger. - Attributes: no_smalltalk (bool): Do not trigger if last utterance is small @@ -297,13 +284,11 @@ class SuggestionTriggerSettings(proto.Message): utterance is END_USER. """ - no_smalltalk = proto.Field(proto.BOOL, number=1) - - only_end_user = proto.Field(proto.BOOL, number=2) + no_smalltalk = proto.Field(proto.BOOL, number=1,) + only_end_user = proto.Field(proto.BOOL, number=2,) class SuggestionFeatureConfig(proto.Message): r"""Config for suggestion features. - Attributes: suggestion_feature (google.cloud.dialogflow_v2.types.SuggestionFeature): The suggestion feature. @@ -327,21 +312,17 @@ class SuggestionFeatureConfig(proto.Message): suggestion_feature = proto.Field( proto.MESSAGE, number=5, message="SuggestionFeature", ) - - enable_event_based_suggestion = proto.Field(proto.BOOL, number=3) - + enable_event_based_suggestion = proto.Field(proto.BOOL, number=3,) suggestion_trigger_settings = proto.Field( proto.MESSAGE, number=10, message="HumanAgentAssistantConfig.SuggestionTriggerSettings", ) - query_config = proto.Field( proto.MESSAGE, number=6, message="HumanAgentAssistantConfig.SuggestionQueryConfig", ) - conversation_model_config = proto.Field( proto.MESSAGE, number=7, @@ -350,7 +331,6 @@ class SuggestionFeatureConfig(proto.Message): class SuggestionConfig(proto.Message): r"""Detail human agent assistant config. - Attributes: feature_configs (Sequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): Configuration of different suggestion @@ -375,12 +355,10 @@ class SuggestionConfig(proto.Message): number=2, message="HumanAgentAssistantConfig.SuggestionFeatureConfig", ) - - group_suggestion_responses = proto.Field(proto.BOOL, number=3) + group_suggestion_responses = proto.Field(proto.BOOL, number=3,) class SuggestionQueryConfig(proto.Message): r"""Config for suggestion query. - Attributes: knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, @@ -434,7 +412,7 @@ class KnowledgeBaseQuerySource(proto.Message): Currently, at most 5 knowledge bases are supported. """ - knowledge_bases = proto.RepeatedField(proto.STRING, number=1) + knowledge_bases = proto.RepeatedField(proto.STRING, number=1,) class DocumentQuerySource(proto.Message): r"""Document source settings. @@ -448,7 +426,7 @@ class DocumentQuerySource(proto.Message): Currently, at most 5 documents are supported. """ - documents = proto.RepeatedField(proto.STRING, number=1) + documents = proto.RepeatedField(proto.STRING, number=1,) class DialogflowQuerySource(proto.Message): r"""Dialogflow source setting. @@ -464,7 +442,7 @@ class DialogflowQuerySource(proto.Message): project. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class ContextFilterSettings(proto.Message): r"""Settings that determine how to filter recent conversation @@ -483,11 +461,9 @@ class ContextFilterSettings(proto.Message): are dropped. """ - drop_handoff_messages = proto.Field(proto.BOOL, number=1) - - drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2) - - drop_ivr_messages = proto.Field(proto.BOOL, number=3) + drop_handoff_messages = proto.Field(proto.BOOL, number=1,) + drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2,) + drop_ivr_messages = proto.Field(proto.BOOL, number=3,) knowledge_base_query_source = proto.Field( proto.MESSAGE, @@ -495,25 +471,20 @@ class ContextFilterSettings(proto.Message): oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource", ) - document_query_source = proto.Field( proto.MESSAGE, number=2, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource", ) - dialogflow_query_source = proto.Field( proto.MESSAGE, number=3, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource", ) - - max_results = proto.Field(proto.INT32, number=4) - - confidence_threshold = proto.Field(proto.FLOAT, number=5) - + max_results = proto.Field(proto.INT32, number=4,) + confidence_threshold = proto.Field(proto.FLOAT, number=5,) context_filter_settings = proto.Field( proto.MESSAGE, number=7, @@ -527,11 +498,11 @@ class ConversationModelConfig(proto.Message): Attributes: model (str): - Required. Conversation model resource name. Format: + Conversation model resource name. Format: ``projects//conversationModels/``. """ - model = proto.Field(proto.STRING, number=1) + model = proto.Field(proto.STRING, number=1,) class MessageAnalysisConfig(proto.Message): r"""Configuration for analyses to run on each conversation @@ -543,6 +514,9 @@ class MessageAnalysisConfig(proto.Message): assist stage `__. If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. enable_sentiment_analysis (bool): Enable sentiment analysis in conversation messages on `agent assist @@ -568,22 +542,18 @@ class MessageAnalysisConfig(proto.Message): [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2.ConversationEvent.new_message_payload]. """ - enable_entity_extraction = proto.Field(proto.BOOL, number=2) - - enable_sentiment_analysis = proto.Field(proto.BOOL, number=3) + enable_entity_extraction = proto.Field(proto.BOOL, number=2,) + enable_sentiment_analysis = proto.Field(proto.BOOL, number=3,) notification_config = proto.Field( proto.MESSAGE, number=2, message="NotificationConfig", ) - human_agent_suggestion_config = proto.Field( proto.MESSAGE, number=3, message=SuggestionConfig, ) - end_user_suggestion_config = proto.Field( proto.MESSAGE, number=4, message=SuggestionConfig, ) - message_analysis_config = proto.Field( proto.MESSAGE, number=5, message=MessageAnalysisConfig, ) @@ -592,6 +562,8 @@ class MessageAnalysisConfig(proto.Message): class HumanAgentHandoffConfig(proto.Message): r"""Defines the hand off to a live agent, typically on which external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. Attributes: live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): @@ -611,11 +583,10 @@ class LivePersonConfig(proto.Message): you input at the login page. """ - account_number = proto.Field(proto.STRING, number=1) + account_number = proto.Field(proto.STRING, number=1,) class SalesforceLiveAgentConfig(proto.Message): r"""Configuration specific to Salesforce Live Agent. - Attributes: organization_id (str): Required. The organization ID of the @@ -632,18 +603,14 @@ class SalesforceLiveAgentConfig(proto.Message): fill in d.la4-c2-phx.salesforceliveagent.com. """ - organization_id = proto.Field(proto.STRING, number=1) - - deployment_id = proto.Field(proto.STRING, number=2) - - button_id = proto.Field(proto.STRING, number=3) - - endpoint_domain = proto.Field(proto.STRING, number=4) + organization_id = proto.Field(proto.STRING, number=1,) + deployment_id = proto.Field(proto.STRING, number=2,) + button_id = proto.Field(proto.STRING, number=3,) + endpoint_domain = proto.Field(proto.STRING, number=4,) live_person_config = proto.Field( proto.MESSAGE, number=1, oneof="agent_service", message=LivePersonConfig, ) - salesforce_live_agent_config = proto.Field( proto.MESSAGE, number=2, @@ -654,7 +621,6 @@ class SalesforceLiveAgentConfig(proto.Message): class NotificationConfig(proto.Message): r"""Defines notification behavior. - Attributes: topic (str): Name of the Pub/Sub topic to publish conversation events @@ -681,14 +647,12 @@ class MessageFormat(proto.Enum): PROTO = 1 JSON = 2 - topic = proto.Field(proto.STRING, number=1) - + topic = proto.Field(proto.STRING, number=1,) message_format = proto.Field(proto.ENUM, number=2, enum=MessageFormat,) class LoggingConfig(proto.Message): r"""Defines logging behavior for conversation lifecycle events. - Attributes: enable_stackdriver_logging (bool): Whether to log conversation events like @@ -698,7 +662,7 @@ class LoggingConfig(proto.Message): protos. """ - enable_stackdriver_logging = proto.Field(proto.BOOL, number=3) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=3,) class SuggestionFeature(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/document.py b/google/cloud/dialogflow_v2/types/document.py index d04fe2188..c65907b64 100644 --- a/google/cloud/dialogflow_v2/types/document.py +++ b/google/cloud/dialogflow_v2/types/document.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -118,7 +115,6 @@ class KnowledgeType(proto.Enum): class ReloadStatus(proto.Message): r"""The status of a reload attempt. - Attributes: time (google.protobuf.timestamp_pb2.Timestamp): The time of a reload attempt. @@ -130,27 +126,18 @@ class ReloadStatus(proto.Message): load. """ - time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) + time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) knowledge_types = proto.RepeatedField(proto.ENUM, number=4, enum=KnowledgeType,) - - content_uri = proto.Field(proto.STRING, number=5, oneof="source") - - raw_content = proto.Field(proto.BYTES, number=9, oneof="source") - - enable_auto_reload = proto.Field(proto.BOOL, number=11) - + content_uri = proto.Field(proto.STRING, number=5, oneof="source",) + raw_content = proto.Field(proto.BYTES, number=9, oneof="source",) + enable_auto_reload = proto.Field(proto.BOOL, number=11,) latest_reload_status = proto.Field(proto.MESSAGE, number=12, message=ReloadStatus,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=7) + metadata = proto.MapField(proto.STRING, proto.STRING, number=7,) class GetDocumentRequest(proto.Message): @@ -163,7 +150,7 @@ class GetDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListDocumentsRequest(proto.Message): @@ -183,11 +170,9 @@ class ListDocumentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListDocumentsResponse(proto.Message): @@ -208,8 +193,7 @@ def raw_page(self): return self documents = proto.RepeatedField(proto.MESSAGE, number=1, message="Document",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateDocumentRequest(proto.Message): @@ -225,8 +209,7 @@ class CreateDocumentRequest(proto.Message): Required. The document to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) document = proto.Field(proto.MESSAGE, number=2, message="Document",) @@ -240,7 +223,7 @@ class DeleteDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateDocumentRequest(proto.Message): @@ -257,8 +240,9 @@ class UpdateDocumentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class ReloadDocumentRequest(proto.Message): @@ -277,9 +261,8 @@ class ReloadDocumentRequest(proto.Message): must have the form ``gs:///``. """ - name = proto.Field(proto.STRING, number=1) - - content_uri = proto.Field(proto.STRING, number=3, oneof="source") + name = proto.Field(proto.STRING, number=1,) + content_uri = proto.Field(proto.STRING, number=3, oneof="source",) class KnowledgeOperationMetadata(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/entity_type.py b/google/cloud/dialogflow_v2/types/entity_type.py index 3d0214e56..acb5cece1 100644 --- a/google/cloud/dialogflow_v2/types/entity_type.py +++ b/google/cloud/dialogflow_v2/types/entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -98,7 +95,6 @@ class AutoExpansionMode(proto.Enum): class Entity(proto.Message): r"""An **entity entry** for an associated entity type. - Attributes: value (str): Required. The primary value associated with this entity @@ -124,21 +120,15 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) kind = proto.Field(proto.ENUM, number=3, enum=Kind,) - auto_expansion_mode = proto.Field(proto.ENUM, number=4, enum=AutoExpansionMode,) - entities = proto.RepeatedField(proto.MESSAGE, number=6, message=Entity,) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) class ListEntityTypesRequest(proto.Message): @@ -164,13 +154,10 @@ class ListEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListEntityTypesResponse(proto.Message): @@ -193,8 +180,7 @@ def raw_page(self): return self entity_types = proto.RepeatedField(proto.MESSAGE, number=1, message="EntityType",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEntityTypeRequest(proto.Message): @@ -213,9 +199,8 @@ class GetEntityTypeRequest(proto.Message): data `__. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateEntityTypeRequest(proto.Message): @@ -236,11 +221,9 @@ class CreateEntityTypeRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type = proto.Field(proto.MESSAGE, number=2, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateEntityTypeRequest(proto.Message): @@ -262,10 +245,10 @@ class UpdateEntityTypeRequest(proto.Message): """ entity_type = proto.Field(proto.MESSAGE, number=1, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteEntityTypeRequest(proto.Message): @@ -278,7 +261,7 @@ class DeleteEntityTypeRequest(proto.Message): ``projects//agent/entityTypes/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateEntityTypesRequest(proto.Message): @@ -309,19 +292,17 @@ class BatchUpdateEntityTypesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type_batch_uri = proto.Field( - proto.STRING, number=2, oneof="entity_type_batch" + proto.STRING, number=2, oneof="entity_type_batch", ) - entity_type_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="entity_type_batch", message="EntityTypeBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) class BatchUpdateEntityTypesResponse(proto.Message): @@ -350,9 +331,8 @@ class BatchDeleteEntityTypesRequest(proto.Message): point to the same agent as ``parent``. """ - parent = proto.Field(proto.STRING, number=1) - - entity_type_names = proto.RepeatedField(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entity_type_names = proto.RepeatedField(proto.STRING, number=2,) class BatchCreateEntitiesRequest(proto.Message): @@ -374,13 +354,11 @@ class BatchCreateEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class BatchUpdateEntitiesRequest(proto.Message): @@ -405,15 +383,14 @@ class BatchUpdateEntitiesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) - - update_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=3,) + update_mask = proto.Field( + proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask, + ) class BatchDeleteEntitiesRequest(proto.Message): @@ -437,11 +414,9 @@ class BatchDeleteEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - - entity_values = proto.RepeatedField(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + entity_values = proto.RepeatedField(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) class EntityTypeBatch(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/environment.py b/google/cloud/dialogflow_v2/types/environment.py index 21f40d80e..204524dc7 100644 --- a/google/cloud/dialogflow_v2/types/environment.py +++ b/google/cloud/dialogflow_v2/types/environment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.dialogflow.v2", - manifest={"Environment", "ListEnvironmentsRequest", "ListEnvironmentsResponse",}, + manifest={ + "Environment", + "TextToSpeechSettings", + "ListEnvironmentsRequest", + "ListEnvironmentsResponse", + "GetEnvironmentRequest", + "CreateEnvironmentRequest", + "UpdateEnvironmentRequest", + "DeleteEnvironmentRequest", + "GetEnvironmentHistoryRequest", + "EnvironmentHistory", + }, ) @@ -51,9 +62,10 @@ class Environment(proto.Message): Attributes: name (str): Output only. The unique identifier of this agent - environment. Format: - ``projects//agent/environments/``. - For Environment ID, "-" is reserved for 'draft' environment. + environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` description (str): Optional. The developer-provided description for this environment. The maximum length is 500 @@ -61,8 +73,10 @@ class Environment(proto.Message): rejected. agent_version (str): Optional. The agent version loaded into this environment. - Format: - ``projects//agent/versions/``. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` state (google.cloud.dialogflow_v2.types.Environment.State): Output only. The state of this environment. This field is read-only, i.e., it cannot be set @@ -71,6 +85,12 @@ class Environment(proto.Message): Output only. The last update time of this environment. This field is read-only, i.e., it cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. """ class State(proto.Enum): @@ -86,15 +106,58 @@ class State(proto.Enum): LOADING = 2 RUNNING = 3 - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + agent_version = proto.Field(proto.STRING, number=3,) + state = proto.Field(proto.ENUM, number=4, enum=State,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + text_to_speech_settings = proto.Field( + proto.MESSAGE, number=7, message="TextToSpeechSettings", + ) + fulfillment = proto.Field( + proto.MESSAGE, number=8, message=gcd_fulfillment.Fulfillment, + ) - description = proto.Field(proto.STRING, number=2) - agent_version = proto.Field(proto.STRING, number=3) +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. - state = proto.Field(proto.ENUM, number=4, enum=State,) + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + enable_text_to_speech = proto.Field(proto.BOOL, number=1,) + output_audio_encoding = proto.Field( + proto.ENUM, number=2, enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field(proto.INT32, number=3,) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) class ListEnvironmentsRequest(proto.Message): @@ -104,7 +167,9 @@ class ListEnvironmentsRequest(proto.Message): Attributes: parent (str): Required. The agent to list all environments from. Format: - ``projects//agent``. + + - ``projects//agent`` + - ``projects//locations//agent`` page_size (int): Optional. The maximum number of items to return in a single page. By default 100 and at @@ -114,11 +179,9 @@ class ListEnvironmentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListEnvironmentsResponse(proto.Message): @@ -141,8 +204,160 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) + environment_id = proto.Field(proto.STRING, number=3,) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field(proto.BOOL, number=3,) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self - next_page_token = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entries = proto.RepeatedField(proto.MESSAGE, number=2, message=Entry,) + next_page_token = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py b/google/cloud/dialogflow_v2/types/fulfillment.py similarity index 77% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py rename to google/cloud/dialogflow_v2/types/fulfillment.py index 85b91ad3b..c867a5c3f 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py +++ b/google/cloud/dialogflow_v2/types/fulfillment.py @@ -19,12 +19,8 @@ __protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'Fulfillment', - 'GetFulfillmentRequest', - 'UpdateFulfillmentRequest', - }, + package="google.cloud.dialogflow.v2", + manifest={"Fulfillment", "GetFulfillmentRequest", "UpdateFulfillmentRequest",}, ) @@ -92,27 +88,11 @@ class GenericWebService(proto.Message): configured by its uri as a regular web service now. """ - uri = proto.Field( - proto.STRING, - number=1, - ) - username = proto.Field( - proto.STRING, - number=2, - ) - password = proto.Field( - proto.STRING, - number=3, - ) - request_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - is_cloud_function = proto.Field( - proto.BOOL, - number=5, - ) + uri = proto.Field(proto.STRING, number=1,) + username = proto.Field(proto.STRING, number=2,) + password = proto.Field(proto.STRING, number=3,) + request_headers = proto.MapField(proto.STRING, proto.STRING, number=4,) + is_cloud_function = proto.Field(proto.BOOL, number=5,) class Feature(proto.Message): r"""Whether fulfillment is enabled for the specific feature. @@ -121,40 +101,21 @@ class Feature(proto.Message): The type of the feature that enabled for fulfillment. """ + class Type(proto.Enum): r"""The type of the feature.""" TYPE_UNSPECIFIED = 0 SMALLTALK = 1 - type_ = proto.Field( - proto.ENUM, - number=1, - enum='Fulfillment.Feature.Type', - ) + type_ = proto.Field(proto.ENUM, number=1, enum="Fulfillment.Feature.Type",) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) generic_web_service = proto.Field( - proto.MESSAGE, - number=3, - oneof='fulfillment', - message=GenericWebService, - ) - enabled = proto.Field( - proto.BOOL, - number=4, - ) - features = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Feature, + proto.MESSAGE, number=3, oneof="fulfillment", message=GenericWebService, ) + enabled = proto.Field(proto.BOOL, number=4,) + features = proto.RepeatedField(proto.MESSAGE, number=5, message=Feature,) class GetFulfillmentRequest(proto.Message): @@ -167,10 +128,7 @@ class GetFulfillmentRequest(proto.Message): ``projects//agent/fulfillment``. """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) class UpdateFulfillmentRequest(proto.Message): @@ -186,15 +144,9 @@ class UpdateFulfillmentRequest(proto.Message): fields will be updated. """ - fulfillment = proto.Field( - proto.MESSAGE, - number=1, - message='Fulfillment', - ) + fulfillment = proto.Field(proto.MESSAGE, number=1, message="Fulfillment",) update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) diff --git a/google/cloud/dialogflow_v2/types/gcs.py b/google/cloud/dialogflow_v2/types/gcs.py index 5f0961da2..8076c8a39 100644 --- a/google/cloud/dialogflow_v2/types/gcs.py +++ b/google/cloud/dialogflow_v2/types/gcs.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py b/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py index 48fdc4371..74a0afacf 100644 --- a/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py +++ b/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import participant as gcd_participant @@ -43,10 +40,8 @@ class HumanAgentAssistantEvent(proto.Message): notification refers to. """ - conversation = proto.Field(proto.STRING, number=1) - - participant = proto.Field(proto.STRING, number=3) - + conversation = proto.Field(proto.STRING, number=1,) + participant = proto.Field(proto.STRING, number=3,) suggestion_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_participant.SuggestionResult, ) diff --git a/google/cloud/dialogflow_v2/types/intent.py b/google/cloud/dialogflow_v2/types/intent.py index 5c7505576..6056300c4 100644 --- a/google/cloud/dialogflow_v2/types/intent.py +++ b/google/cloud/dialogflow_v2/types/intent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -178,7 +175,6 @@ class WebhookState(proto.Enum): class TrainingPhrase(proto.Message): r"""Represents an example that the agent is trained on. - Attributes: name (str): Output only. The unique identifier of this @@ -225,7 +221,6 @@ class Type(proto.Enum): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -246,27 +241,20 @@ class Part(proto.Message): part with the API, you must set this to true. """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - alias = proto.Field(proto.STRING, number=3) - - user_defined = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + alias = proto.Field(proto.STRING, number=3,) + user_defined = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum="Intent.TrainingPhrase.Type",) - parts = proto.RepeatedField( proto.MESSAGE, number=3, message="Intent.TrainingPhrase.Part", ) - - times_added_count = proto.Field(proto.INT32, number=4) + times_added_count = proto.Field(proto.INT32, number=4,) class Parameter(proto.Message): r"""Represents intent parameters. - Attributes: name (str): The unique identifier of this parameter. @@ -304,21 +292,14 @@ class Parameter(proto.Message): represents a list of values. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - value = proto.Field(proto.STRING, number=3) - - default_value = proto.Field(proto.STRING, number=4) - - entity_type_display_name = proto.Field(proto.STRING, number=5) - - mandatory = proto.Field(proto.BOOL, number=6) - - prompts = proto.RepeatedField(proto.STRING, number=7) - - is_list = proto.Field(proto.BOOL, number=8) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + value = proto.Field(proto.STRING, number=3,) + default_value = proto.Field(proto.STRING, number=4,) + entity_type_display_name = proto.Field(proto.STRING, number=5,) + mandatory = proto.Field(proto.BOOL, number=6,) + prompts = proto.RepeatedField(proto.STRING, number=7,) + is_list = proto.Field(proto.BOOL, number=8,) class Message(proto.Message): r"""A rich response message. Corresponds to the intent ``Response`` @@ -381,18 +362,16 @@ class Platform(proto.Enum): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Optional. The collection of the agent's responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class Image(proto.Message): r"""The image response message. - Attributes: image_uri (str): Optional. The public URI to an image file. @@ -401,13 +380,11 @@ class Image(proto.Message): be used for accessibility, e.g., screen readers. """ - image_uri = proto.Field(proto.STRING, number=1) - - accessibility_text = proto.Field(proto.STRING, number=2) + image_uri = proto.Field(proto.STRING, number=1,) + accessibility_text = proto.Field(proto.STRING, number=2,) class QuickReplies(proto.Message): r"""The quick replies response message. - Attributes: title (str): Optional. The title of the collection of @@ -416,13 +393,11 @@ class QuickReplies(proto.Message): Optional. The collection of quick replies. """ - title = proto.Field(proto.STRING, number=1) - - quick_replies = proto.RepeatedField(proto.STRING, number=2) + title = proto.Field(proto.STRING, number=1,) + quick_replies = proto.RepeatedField(proto.STRING, number=2,) class Card(proto.Message): r"""The card response message. - Attributes: title (str): Optional. The title of the card. @@ -437,7 +412,6 @@ class Card(proto.Message): class Button(proto.Message): r"""Contains information about a button. - Attributes: text (str): Optional. The text to show on the button. @@ -446,23 +420,18 @@ class Button(proto.Message): Dialogflow API or a URI to open. """ - text = proto.Field(proto.STRING, number=1) - - postback = proto.Field(proto.STRING, number=2) - - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - image_uri = proto.Field(proto.STRING, number=3) + text = proto.Field(proto.STRING, number=1,) + postback = proto.Field(proto.STRING, number=2,) + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + image_uri = proto.Field(proto.STRING, number=3,) buttons = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.Card.Button", ) class SimpleResponse(proto.Message): r"""The simple response message containing speech or text. - Attributes: text_to_speech (str): One of text_to_speech or ssml must be provided. The plain @@ -475,11 +444,9 @@ class SimpleResponse(proto.Message): Optional. The text to display. """ - text_to_speech = proto.Field(proto.STRING, number=1) - - ssml = proto.Field(proto.STRING, number=2) - - display_text = proto.Field(proto.STRING, number=3) + text_to_speech = proto.Field(proto.STRING, number=1,) + ssml = proto.Field(proto.STRING, number=2,) + display_text = proto.Field(proto.STRING, number=3,) class SimpleResponses(proto.Message): r"""The collection of simple response candidates. This message in @@ -498,7 +465,6 @@ class SimpleResponses(proto.Message): class BasicCard(proto.Message): r"""The basic card message. Useful for displaying information. - Attributes: title (str): Optional. The title of the card. @@ -515,7 +481,6 @@ class BasicCard(proto.Message): class Button(proto.Message): r"""The button object that appears at the bottom of a card. - Attributes: title (str): Required. The title of the button. @@ -526,32 +491,26 @@ class Button(proto.Message): class OpenUriAction(proto.Message): r"""Opens the given URI. - Attributes: uri (str): Required. The HTTP or HTTPS scheme URI. """ - uri = proto.Field(proto.STRING, number=1) - - title = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + title = proto.Field(proto.STRING, number=1,) open_uri_action = proto.Field( proto.MESSAGE, number=2, message="Intent.Message.BasicCard.Button.OpenUriAction", ) - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - formatted_text = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + formatted_text = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.BasicCard.Button", ) @@ -566,11 +525,10 @@ class Suggestion(proto.Message): suggestion chip. """ - title = proto.Field(proto.STRING, number=1) + title = proto.Field(proto.STRING, number=1,) class Suggestions(proto.Message): r"""The collection of suggestions. - Attributes: suggestions (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): Required. The list of suggested replies. @@ -593,13 +551,11 @@ class LinkOutSuggestion(proto.Message): when the user taps the suggestion chip. """ - destination_name = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) + destination_name = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) class ListSelect(proto.Message): r"""The card for presenting a list of options to select from. - Attributes: title (str): Optional. The overall title of the list. @@ -611,7 +567,6 @@ class ListSelect(proto.Message): class Item(proto.Message): r"""An item in the list. - Attributes: info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): Required. Additional information about this @@ -627,26 +582,20 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - title = proto.Field(proto.STRING, number=1) - + title = proto.Field(proto.STRING, number=1,) items = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.ListSelect.Item", ) - - subtitle = proto.Field(proto.STRING, number=3) + subtitle = proto.Field(proto.STRING, number=3,) class CarouselSelect(proto.Message): r"""The card for presenting a carousel of options to select from. - Attributes: items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): Required. Carousel items. @@ -654,7 +603,6 @@ class CarouselSelect(proto.Message): class Item(proto.Message): r"""An item in the carousel. - Attributes: info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): Required. Additional info about the option @@ -670,11 +618,8 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) @@ -696,13 +641,11 @@ class SelectItemInfo(proto.Message): used to trigger this item in dialog. """ - key = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + key = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class MediaContent(proto.Message): r"""The media content card for Actions on Google. - Attributes: media_type (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaType): Optional. What type of media is the content @@ -718,7 +661,6 @@ class ResponseMediaType(proto.Enum): class ResponseMediaObject(proto.Message): r"""Response media object for media content card. - Attributes: name (str): Required. Name of media card. @@ -734,32 +676,27 @@ class ResponseMediaObject(proto.Message): Required. Url where the media is stored. """ - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) large_image = proto.Field( proto.MESSAGE, number=3, oneof="image", message="Intent.Message.Image", ) - icon = proto.Field( proto.MESSAGE, number=4, oneof="image", message="Intent.Message.Image", ) - - content_url = proto.Field(proto.STRING, number=5) + content_url = proto.Field(proto.STRING, number=5,) media_type = proto.Field( proto.ENUM, number=1, enum="Intent.Message.MediaContent.ResponseMediaType", ) - media_objects = proto.RepeatedField( proto.MESSAGE, number=2, @@ -794,7 +731,6 @@ class ImageDisplayOptions(proto.Enum): class BrowseCarouselCardItem(proto.Message): r"""Browsing carousel tile - Attributes: open_uri_action (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): Required. Action to present to the user. @@ -814,7 +750,6 @@ class BrowseCarouselCardItem(proto.Message): class OpenUrlAction(proto.Message): r"""Actions on Google action to open a given url. - Attributes: url (str): Required. URL @@ -830,8 +765,7 @@ class UrlTypeHint(proto.Enum): AMP_ACTION = 1 AMP_CONTENT = 2 - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) url_type_hint = proto.Field( proto.ENUM, number=3, @@ -843,23 +777,18 @@ class UrlTypeHint(proto.Enum): number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - - footer = proto.Field(proto.STRING, number=5) + footer = proto.Field(proto.STRING, number=5,) items = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem", ) - image_display_options = proto.Field( proto.ENUM, number=2, @@ -868,7 +797,6 @@ class UrlTypeHint(proto.Enum): class TableCard(proto.Message): r"""Table card for Actions on Google. - Attributes: title (str): Required. Title of the card. @@ -886,22 +814,17 @@ class TableCard(proto.Message): Optional. List of buttons for the card. """ - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) image = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.Image", ) - column_properties = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.ColumnProperties", ) - rows = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.TableCardRow", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=6, message="Intent.Message.BasicCard.Button", ) @@ -925,8 +848,7 @@ class HorizontalAlignment(proto.Enum): CENTER = 2 TRAILING = 3 - header = proto.Field(proto.STRING, number=1) - + header = proto.Field(proto.STRING, number=1,) horizontal_alignment = proto.Field( proto.ENUM, number=2, @@ -949,8 +871,7 @@ class TableCardRow(proto.Message): cells = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.TableCardCell", ) - - divider_after = proto.Field(proto.BOOL, number=2) + divider_after = proto.Field(proto.BOOL, number=2,) class TableCardCell(proto.Message): r"""Cell of @@ -961,99 +882,84 @@ class TableCardCell(proto.Message): Required. Text in this cell. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) text = proto.Field( proto.MESSAGE, number=1, oneof="message", message="Intent.Message.Text", ) - image = proto.Field( proto.MESSAGE, number=2, oneof="message", message="Intent.Message.Image", ) - quick_replies = proto.Field( proto.MESSAGE, number=3, oneof="message", message="Intent.Message.QuickReplies", ) - card = proto.Field( proto.MESSAGE, number=4, oneof="message", message="Intent.Message.Card", ) - payload = proto.Field( - proto.MESSAGE, number=5, oneof="message", message=struct.Struct, + proto.MESSAGE, number=5, oneof="message", message=struct_pb2.Struct, ) - simple_responses = proto.Field( proto.MESSAGE, number=7, oneof="message", message="Intent.Message.SimpleResponses", ) - basic_card = proto.Field( proto.MESSAGE, number=8, oneof="message", message="Intent.Message.BasicCard", ) - suggestions = proto.Field( proto.MESSAGE, number=9, oneof="message", message="Intent.Message.Suggestions", ) - link_out_suggestion = proto.Field( proto.MESSAGE, number=10, oneof="message", message="Intent.Message.LinkOutSuggestion", ) - list_select = proto.Field( proto.MESSAGE, number=11, oneof="message", message="Intent.Message.ListSelect", ) - carousel_select = proto.Field( proto.MESSAGE, number=12, oneof="message", message="Intent.Message.CarouselSelect", ) - browse_carousel_card = proto.Field( proto.MESSAGE, number=22, oneof="message", message="Intent.Message.BrowseCarouselCard", ) - table_card = proto.Field( proto.MESSAGE, number=23, oneof="message", message="Intent.Message.TableCard", ) - media_content = proto.Field( proto.MESSAGE, number=24, oneof="message", message="Intent.Message.MediaContent", ) - platform = proto.Field(proto.ENUM, number=6, enum="Intent.Message.Platform",) class FollowupIntentInfo(proto.Message): r"""Represents a single followup intent in the chain. - Attributes: followup_intent_name (str): The unique identifier of the followup intent. Format: @@ -1063,54 +969,34 @@ class FollowupIntentInfo(proto.Message): Format: ``projects//agent/intents/``. """ - followup_intent_name = proto.Field(proto.STRING, number=1) - - parent_followup_intent_name = proto.Field(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + followup_intent_name = proto.Field(proto.STRING, number=1,) + parent_followup_intent_name = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) webhook_state = proto.Field(proto.ENUM, number=6, enum=WebhookState,) - - priority = proto.Field(proto.INT32, number=3) - - is_fallback = proto.Field(proto.BOOL, number=4) - - ml_disabled = proto.Field(proto.BOOL, number=19) - - live_agent_handoff = proto.Field(proto.BOOL, number=20) - - end_interaction = proto.Field(proto.BOOL, number=21) - - input_context_names = proto.RepeatedField(proto.STRING, number=7) - - events = proto.RepeatedField(proto.STRING, number=8) - + priority = proto.Field(proto.INT32, number=3,) + is_fallback = proto.Field(proto.BOOL, number=4,) + ml_disabled = proto.Field(proto.BOOL, number=19,) + live_agent_handoff = proto.Field(proto.BOOL, number=20,) + end_interaction = proto.Field(proto.BOOL, number=21,) + input_context_names = proto.RepeatedField(proto.STRING, number=7,) + events = proto.RepeatedField(proto.STRING, number=8,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=9, message=TrainingPhrase, ) - - action = proto.Field(proto.STRING, number=10) - + action = proto.Field(proto.STRING, number=10,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message=context.Context, ) - - reset_contexts = proto.Field(proto.BOOL, number=12) - + reset_contexts = proto.Field(proto.BOOL, number=12,) parameters = proto.RepeatedField(proto.MESSAGE, number=13, message=Parameter,) - messages = proto.RepeatedField(proto.MESSAGE, number=14, message=Message,) - default_response_platforms = proto.RepeatedField( proto.ENUM, number=15, enum=Message.Platform, ) - - root_followup_intent_name = proto.Field(proto.STRING, number=16) - - parent_followup_intent_name = proto.Field(proto.STRING, number=17) - + root_followup_intent_name = proto.Field(proto.STRING, number=16,) + parent_followup_intent_name = proto.Field(proto.STRING, number=17,) followup_intent_info = proto.RepeatedField( proto.MESSAGE, number=18, message=FollowupIntentInfo, ) @@ -1142,15 +1028,11 @@ class ListIntentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) class ListIntentsResponse(proto.Message): @@ -1172,8 +1054,7 @@ def raw_page(self): return self intents = proto.RepeatedField(proto.MESSAGE, number=1, message="Intent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetIntentRequest(proto.Message): @@ -1195,10 +1076,8 @@ class GetIntentRequest(proto.Message): returned intent. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) @@ -1223,12 +1102,9 @@ class CreateIntentRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intent = proto.Field(proto.MESSAGE, number=2, message="Intent",) - - language_code = proto.Field(proto.STRING, number=3) - + language_code = proto.Field(proto.STRING, number=3,) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1254,11 +1130,10 @@ class UpdateIntentRequest(proto.Message): """ intent = proto.Field(proto.MESSAGE, number=1, message="Intent",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1274,12 +1149,11 @@ class DeleteIntentRequest(proto.Message): ``projects//agent/intents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateIntentsRequest(proto.Message): r""" - Attributes: parent (str): Required. The name of the agent to update or create intents @@ -1307,18 +1181,15 @@ class BatchUpdateIntentsRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - - intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch") - + parent = proto.Field(proto.STRING, number=1,) + intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch",) intent_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="intent_batch", message="IntentBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=6, enum="IntentView",) @@ -1347,14 +1218,12 @@ class BatchDeleteIntentsRequest(proto.Message): ``name`` must be filled in. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intents = proto.RepeatedField(proto.MESSAGE, number=2, message="Intent",) class IntentBatch(proto.Message): r"""This message is a wrapper around a collection of intents. - Attributes: intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): A collection of intents. diff --git a/google/cloud/dialogflow_v2/types/knowledge_base.py b/google/cloud/dialogflow_v2/types/knowledge_base.py index 659be2ce6..c26345d64 100644 --- a/google/cloud/dialogflow_v2/types/knowledge_base.py +++ b/google/cloud/dialogflow_v2/types/knowledge_base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -65,11 +62,9 @@ class KnowledgeBase(proto.Message): language code en-us applies. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=4,) class ListKnowledgeBasesRequest(proto.Message): @@ -88,11 +83,9 @@ class ListKnowledgeBasesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListKnowledgeBasesResponse(proto.Message): @@ -115,8 +108,7 @@ def raw_page(self): knowledge_bases = proto.RepeatedField( proto.MESSAGE, number=1, message="KnowledgeBase", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetKnowledgeBaseRequest(proto.Message): @@ -129,7 +121,7 @@ class GetKnowledgeBaseRequest(proto.Message): ``projects//locations//knowledgeBases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateKnowledgeBaseRequest(proto.Message): @@ -144,8 +136,7 @@ class CreateKnowledgeBaseRequest(proto.Message): Required. The knowledge base to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) knowledge_base = proto.Field(proto.MESSAGE, number=2, message="KnowledgeBase",) @@ -163,9 +154,8 @@ class DeleteKnowledgeBaseRequest(proto.Message): base are also deleted. """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class UpdateKnowledgeBaseRequest(proto.Message): @@ -182,8 +172,9 @@ class UpdateKnowledgeBaseRequest(proto.Message): """ knowledge_base = proto.Field(proto.MESSAGE, number=1, message="KnowledgeBase",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/participant.py b/google/cloud/dialogflow_v2/types/participant.py index e965b4a09..7f5805c42 100644 --- a/google/cloud/dialogflow_v2/types/participant.py +++ b/google/cloud/dialogflow_v2/types/participant.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -83,16 +80,13 @@ class Role(proto.Enum): AUTOMATED_AGENT = 2 END_USER = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) role = proto.Field(proto.ENUM, number=2, enum=Role,) - - sip_recording_media_label = proto.Field(proto.STRING, number=6) + sip_recording_media_label = proto.Field(proto.STRING, number=6,) class Message(proto.Message): r"""Represents a message posted into a conversation. - Attributes: name (str): The unique identifier of the message. Format: @@ -115,18 +109,12 @@ class Message(proto.Message): Output only. The annotation for the message. """ - name = proto.Field(proto.STRING, number=1) - - content = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - participant = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + content = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + participant = proto.Field(proto.STRING, number=4,) participant_role = proto.Field(proto.ENUM, number=5, enum="Participant.Role",) - - create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) message_annotation = proto.Field( proto.MESSAGE, number=7, message="MessageAnnotation", ) @@ -145,8 +133,7 @@ class CreateParticipantRequest(proto.Message): Required. The participant to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) participant = proto.Field(proto.MESSAGE, number=2, message="Participant",) @@ -160,7 +147,7 @@ class GetParticipantRequest(proto.Message): ``projects//locations//conversations//participants/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListParticipantsRequest(proto.Message): @@ -181,11 +168,9 @@ class ListParticipantsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListParticipantsResponse(proto.Message): @@ -206,8 +191,7 @@ def raw_page(self): return self participants = proto.RepeatedField(proto.MESSAGE, number=1, message="Participant",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateParticipantRequest(proto.Message): @@ -223,8 +207,9 @@ class UpdateParticipantRequest(proto.Message): """ participant = proto.Field(proto.MESSAGE, number=1, message="Participant",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class AnalyzeContentRequest(proto.Message): @@ -256,25 +241,20 @@ class AnalyzeContentRequest(proto.Message): only idempotent if a ``request_id`` is provided. """ - participant = proto.Field(proto.STRING, number=1) - + participant = proto.Field(proto.STRING, number=1,) text_input = proto.Field( proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) - reply_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) - query_params = proto.Field( proto.MESSAGE, number=9, message=session.QueryParameters, ) - - request_id = proto.Field(proto.STRING, number=11) + request_id = proto.Field(proto.STRING, number=11,) class DtmfParameters(proto.Message): @@ -287,7 +267,7 @@ class DtmfParameters(proto.Message): in the next request. """ - accepts_dtmf_input = proto.Field(proto.BOOL, number=1) + accepts_dtmf_input = proto.Field(proto.BOOL, number=1,) class AnalyzeContentResponse(proto.Message): @@ -337,24 +317,18 @@ class AnalyzeContentResponse(proto.Message): Indicates the parameters of DTMF. """ - reply_text = proto.Field(proto.STRING, number=1) - + reply_text = proto.Field(proto.STRING, number=1,) reply_audio = proto.Field(proto.MESSAGE, number=2, message="OutputAudio",) - automated_agent_reply = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentReply", ) - message = proto.Field(proto.MESSAGE, number=5, message="Message",) - human_agent_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=6, message="SuggestionResult", ) - end_user_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=7, message="SuggestionResult", ) - dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) @@ -381,11 +355,9 @@ class SuggestArticlesRequest(proto.Message): 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestArticlesResponse(proto.Message): @@ -414,10 +386,8 @@ class SuggestArticlesResponse(proto.Message): article_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="ArticleAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersRequest(proto.Message): @@ -442,11 +412,9 @@ class SuggestFaqAnswersRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersResponse(proto.Message): @@ -472,10 +440,8 @@ class SuggestFaqAnswersResponse(proto.Message): """ faq_answers = proto.RepeatedField(proto.MESSAGE, number=1, message="FaqAnswer",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class OutputAudio(proto.Message): @@ -493,13 +459,11 @@ class OutputAudio(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class AutomatedAgentReply(proto.Message): r"""Represents a response from an automated agent. - Attributes: detect_intent_response (google.cloud.dialogflow_v2.types.DetectIntentResponse): Response of the Dialogflow @@ -514,7 +478,6 @@ class AutomatedAgentReply(proto.Message): class ArticleAnswer(proto.Message): r"""Represents article answer. - Attributes: title (str): The article title. @@ -537,22 +500,16 @@ class ArticleAnswer(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents answer from "frequently asked questions". - Attributes: answer (str): The piece of text from the ``source`` knowledge base @@ -577,17 +534,12 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class SuggestionResult(proto.Message): @@ -610,16 +562,14 @@ class SuggestionResult(proto.Message): """ error = proto.Field( - proto.MESSAGE, number=1, oneof="suggestion_response", message=status.Status, + proto.MESSAGE, number=1, oneof="suggestion_response", message=status_pb2.Status, ) - suggest_articles_response = proto.Field( proto.MESSAGE, number=2, oneof="suggestion_response", message="SuggestArticlesResponse", ) - suggest_faq_answers_response = proto.Field( proto.MESSAGE, number=3, @@ -658,16 +608,13 @@ class AnnotatedMessagePart(proto.Message): """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct.Value,) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Value,) class MessageAnnotation(proto.Message): r"""Represents the result of annotation for the message. - Attributes: parts (Sequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): The collection of annotated message parts ordered by their @@ -681,8 +628,7 @@ class MessageAnnotation(proto.Message): parts = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotatedMessagePart", ) - - contain_entities = proto.Field(proto.BOOL, number=2) + contain_entities = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/session.py b/google/cloud/dialogflow_v2/types/session.py index f7bebda23..e48ead899 100644 --- a/google/cloud/dialogflow_v2/types/session.py +++ b/google/cloud/dialogflow_v2/types/session.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import audio_config as gcd_audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent as gcd_intent from google.cloud.dialogflow_v2.types import session_entity_type -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -51,7 +48,6 @@ class DetectIntentRequest(proto.Message): r"""The request to detect user's intent. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -108,26 +104,20 @@ class DetectIntentRequest(proto.Message): minute of speech audio data. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=5) + input_audio = proto.Field(proto.BYTES, number=5,) class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): The unique identifier of the response. It can @@ -156,14 +146,10 @@ class DetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - - webhook_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=4) - + webhook_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -171,7 +157,6 @@ class DetectIntentResponse(proto.Message): class QueryParameters(proto.Message): r"""Represents the parameters of the conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -218,25 +203,18 @@ class QueryParameters(proto.Message): Since", "If-None-Match", "X-Forwarded-For", etc. """ - time_zone = proto.Field(proto.STRING, number=1) - - geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) - + time_zone = proto.Field(proto.STRING, number=1,) + geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) contexts = proto.RepeatedField(proto.MESSAGE, number=3, message=context.Context,) - - reset_contexts = proto.Field(proto.BOOL, number=4) - + reset_contexts = proto.Field(proto.BOOL, number=4,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=5, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - + payload = proto.Field(proto.MESSAGE, number=6, message=struct_pb2.Struct,) sentiment_analysis_request_config = proto.Field( proto.MESSAGE, number=10, message="SentimentAnalysisRequestConfig", ) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14,) class QueryInput(proto.Message): @@ -264,9 +242,7 @@ class QueryInput(proto.Message): oneof="input", message=gcd_audio_config.InputAudioConfig, ) - text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - event = proto.Field(proto.MESSAGE, number=3, oneof="input", message="EventInput",) @@ -386,38 +362,24 @@ class QueryResult(proto.Message): request. """ - query_text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=15) - - speech_recognition_confidence = proto.Field(proto.FLOAT, number=2) - - action = proto.Field(proto.STRING, number=3) - - parameters = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - all_required_params_present = proto.Field(proto.BOOL, number=5) - - fulfillment_text = proto.Field(proto.STRING, number=6) - + query_text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=15,) + speech_recognition_confidence = proto.Field(proto.FLOAT, number=2,) + action = proto.Field(proto.STRING, number=3,) + parameters = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + all_required_params_present = proto.Field(proto.BOOL, number=5,) + fulfillment_text = proto.Field(proto.STRING, number=6,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_intent.Intent.Message, ) - - webhook_source = proto.Field(proto.STRING, number=8) - - webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) - + webhook_source = proto.Field(proto.STRING, number=8,) + webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=10, message=context.Context, ) - intent = proto.Field(proto.MESSAGE, number=11, message=gcd_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=12) - - diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct.Struct,) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=12,) + diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) @@ -527,23 +489,17 @@ class StreamingDetectIntentRequest(proto.Message): exceed 1 minute. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - - single_utterance = proto.Field(proto.BOOL, number=4) - + single_utterance = proto.Field(proto.BOOL, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=6) + input_audio = proto.Field(proto.BYTES, number=6,) class StreamingDetectIntentResponse(proto.Message): @@ -590,18 +546,13 @@ class StreamingDetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) recognition_result = proto.Field( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - query_result = proto.Field(proto.MESSAGE, number=3, message="QueryResult",) - - webhook_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=5) - + webhook_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=5,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -681,23 +632,19 @@ class MessageType(proto.Enum): END_OF_SINGLE_UTTERANCE = 2 message_type = proto.Field(proto.ENUM, number=1, enum=MessageType,) - - transcript = proto.Field(proto.STRING, number=2) - - is_final = proto.Field(proto.BOOL, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - + transcript = proto.Field(proto.STRING, number=2,) + is_final = proto.Field(proto.BOOL, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) speech_word_info = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_audio_config.SpeechWordInfo, ) - - speech_end_offset = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) + speech_end_offset = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration, + ) class TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -712,9 +659,8 @@ class TextInput(proto.Message): specify the same language. """ - text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class EventInput(proto.Message): @@ -756,16 +702,13 @@ class EventInput(proto.Message): specify the same language. """ - name = proto.Field(proto.STRING, number=1) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - language_code = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + language_code = proto.Field(proto.STRING, number=3,) class SentimentAnalysisRequestConfig(proto.Message): r"""Configures the types of sentiment analysis to perform. - Attributes: analyze_query_text_sentiment (bool): Instructs the service to perform sentiment analysis on @@ -773,7 +716,7 @@ class SentimentAnalysisRequestConfig(proto.Message): performed on ``query_text``. """ - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1,) class SentimentAnalysisResult(proto.Message): @@ -814,9 +757,8 @@ class Sentiment(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/session_entity_type.py b/google/cloud/dialogflow_v2/types/session_entity_type.py index 978eb6056..619b7a8c9 100644 --- a/google/cloud/dialogflow_v2/types/session_entity_type.py +++ b/google/cloud/dialogflow_v2/types/session_entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import entity_type -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -76,10 +73,8 @@ class EntityOverrideMode(proto.Enum): ENTITY_OVERRIDE_MODE_OVERRIDE = 1 ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) entity_override_mode = proto.Field(proto.ENUM, number=2, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=3, message=entity_type.EntityType.Entity, ) @@ -107,11 +102,9 @@ class ListSessionEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSessionEntityTypesResponse(proto.Message): @@ -136,8 +129,7 @@ def raw_page(self): session_entity_types = proto.RepeatedField( proto.MESSAGE, number=1, message="SessionEntityType", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetSessionEntityTypeRequest(proto.Message): @@ -155,7 +147,7 @@ class GetSessionEntityTypeRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -175,8 +167,7 @@ class CreateSessionEntityTypeRequest(proto.Message): Required. The session entity type to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) session_entity_type = proto.Field( proto.MESSAGE, number=2, message="SessionEntityType", ) @@ -197,8 +188,9 @@ class UpdateSessionEntityTypeRequest(proto.Message): session_entity_type = proto.Field( proto.MESSAGE, number=1, message="SessionEntityType", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteSessionEntityTypeRequest(proto.Message): @@ -216,7 +208,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/validation_result.py b/google/cloud/dialogflow_v2/types/validation_result.py index a1d181327..2e3ae1ea5 100644 --- a/google/cloud/dialogflow_v2/types/validation_result.py +++ b/google/cloud/dialogflow_v2/types/validation_result.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class ValidationError(proto.Message): r"""Represents a single validation error. - Attributes: severity (google.cloud.dialogflow_v2.types.ValidationError.Severity): The severity of the error. @@ -63,15 +60,12 @@ class Severity(proto.Enum): CRITICAL = 4 severity = proto.Field(proto.ENUM, number=1, enum=Severity,) - - entries = proto.RepeatedField(proto.STRING, number=3) - - error_message = proto.Field(proto.STRING, number=4) + entries = proto.RepeatedField(proto.STRING, number=3,) + error_message = proto.Field(proto.STRING, number=4,) class ValidationResult(proto.Message): r"""Represents the output of agent validation. - Attributes: validation_errors (Sequence[google.cloud.dialogflow_v2.types.ValidationError]): Contains all validation errors. diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py b/google/cloud/dialogflow_v2/types/version.py similarity index 79% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py rename to google/cloud/dialogflow_v2/types/version.py index aad1a9afa..6400e0445 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py +++ b/google/cloud/dialogflow_v2/types/version.py @@ -20,15 +20,15 @@ __protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', + package="google.cloud.dialogflow.v2", manifest={ - 'Version', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'GetVersionRequest', - 'CreateVersionRequest', - 'UpdateVersionRequest', - 'DeleteVersionRequest', + "Version", + "ListVersionsRequest", + "ListVersionsResponse", + "GetVersionRequest", + "CreateVersionRequest", + "UpdateVersionRequest", + "DeleteVersionRequest", }, ) @@ -77,6 +77,7 @@ class Version(proto.Message): field is read-only and cannot be set by create and update methods. """ + class VersionStatus(proto.Enum): r"""The status of a version.""" VERSION_STATUS_UNSPECIFIED = 0 @@ -84,28 +85,11 @@ class VersionStatus(proto.Enum): READY = 2 FAILED = 3 - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - version_number = proto.Field( - proto.INT32, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - status = proto.Field( - proto.ENUM, - number=6, - enum=VersionStatus, - ) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + version_number = proto.Field(proto.INT32, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.ENUM, number=6, enum=VersionStatus,) class ListVersionsRequest(proto.Message): @@ -128,18 +112,9 @@ class ListVersionsRequest(proto.Message): list request. """ - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListVersionsResponse(proto.Message): @@ -161,15 +136,8 @@ class ListVersionsResponse(proto.Message): def raw_page(self): return self - versions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Version', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) + versions = proto.RepeatedField(proto.MESSAGE, number=1, message="Version",) + next_page_token = proto.Field(proto.STRING, number=2,) class GetVersionRequest(proto.Message): @@ -184,10 +152,7 @@ class GetVersionRequest(proto.Message): - ``projects//locations//agent/versions/`` """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) class CreateVersionRequest(proto.Message): @@ -205,15 +170,8 @@ class CreateVersionRequest(proto.Message): Required. The version to create. """ - parent = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message='Version', - ) + parent = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.MESSAGE, number=2, message="Version",) class UpdateVersionRequest(proto.Message): @@ -231,15 +189,9 @@ class UpdateVersionRequest(proto.Message): get updated. """ - version = proto.Field( - proto.MESSAGE, - number=1, - message='Version', - ) + version = proto.Field(proto.MESSAGE, number=1, message="Version",) update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) @@ -256,10 +208,7 @@ class DeleteVersionRequest(proto.Message): - ``projects//locations//agent/versions/`` """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/webhook.py b/google/cloud/dialogflow_v2/types/webhook.py index e7776734c..8c96b6676 100644 --- a/google/cloud/dialogflow_v2/types/webhook.py +++ b/google/cloud/dialogflow_v2/types/webhook.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import session as gcd_session from google.cloud.dialogflow_v2.types import session_entity_type -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -33,7 +30,6 @@ class WebhookRequest(proto.Message): r"""The request message for a webhook call. - Attributes: session (str): The unique identifier of detectIntent request session. Can @@ -53,14 +49,11 @@ class WebhookRequest(proto.Message): passed to ``[Streaming]DetectIntent`` call. """ - session = proto.Field(proto.STRING, number=4) - - response_id = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=4,) + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field( proto.MESSAGE, number=2, message=gcd_session.QueryResult, ) - original_detect_intent_request = proto.Field( proto.MESSAGE, number=3, message="OriginalDetectIntentRequest", ) @@ -136,24 +129,18 @@ class WebhookResponse(proto.Message): management methods. """ - fulfillment_text = proto.Field(proto.STRING, number=1) - + fulfillment_text = proto.Field(proto.STRING, number=1,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=intent.Intent.Message, ) - - source = proto.Field(proto.STRING, number=3) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + source = proto.Field(proto.STRING, number=3,) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=5, message=context.Context, ) - followup_event_input = proto.Field( proto.MESSAGE, number=6, message=gcd_session.EventInput, ) - session_entity_types = proto.RepeatedField( proto.MESSAGE, number=10, message=session_entity_type.SessionEntityType, ) @@ -193,11 +180,9 @@ class OriginalDetectIntentRequest(proto.Message): Essentials Edition agents. """ - source = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - payload = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + source = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + payload = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/__init__.py b/google/cloud/dialogflow_v2beta1/__init__.py index 52d53f6ed..a31bffd6d 100644 --- a/google/cloud/dialogflow_v2beta1/__init__.py +++ b/google/cloud/dialogflow_v2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,36 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + from .types.agent import Agent from .types.agent import DeleteAgentRequest from .types.agent import ExportAgentRequest @@ -49,19 +66,19 @@ from .types.answer_record import ListAnswerRecordsRequest from .types.answer_record import ListAnswerRecordsResponse from .types.answer_record import UpdateAnswerRecordRequest -from .types.audio_config import AudioEncoding from .types.audio_config import InputAudioConfig from .types.audio_config import OutputAudioConfig -from .types.audio_config import OutputAudioEncoding from .types.audio_config import SpeechContext -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechToTextConfig from .types.audio_config import SpeechWordInfo -from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig -from .types.audio_config import TelephonyDtmf from .types.audio_config import TelephonyDtmfEvents from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender +from .types.audio_config import TelephonyDtmf from .types.context import Context from .types.context import CreateContextRequest from .types.context import DeleteAllContextsRequest @@ -99,9 +116,9 @@ from .types.document import DeleteDocumentRequest from .types.document import Document from .types.document import GetDocumentRequest -from .types.document import ImportDocumentTemplate from .types.document import ImportDocumentsRequest from .types.document import ImportDocumentsResponse +from .types.document import ImportDocumentTemplate from .types.document import KnowledgeOperationMetadata from .types.document import ListDocumentsRequest from .types.document import ListDocumentsResponse @@ -121,9 +138,19 @@ from .types.entity_type import ListEntityTypesRequest from .types.entity_type import ListEntityTypesResponse from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest from .types.environment import ListEnvironmentsRequest from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest from .types.gcs import GcsSource from .types.gcs import GcsSources from .types.human_agent_assistant_event import HumanAgentAssistantEvent @@ -135,10 +162,10 @@ from .types.intent import GetIntentRequest from .types.intent import Intent from .types.intent import IntentBatch -from .types.intent import IntentView from .types.intent import ListIntentsRequest from .types.intent import ListIntentsResponse from .types.intent import UpdateIntentRequest +from .types.intent import IntentView from .types.knowledge_base import CreateKnowledgeBaseRequest from .types.knowledge_base import DeleteKnowledgeBaseRequest from .types.knowledge_base import GetKnowledgeBaseRequest @@ -171,11 +198,11 @@ from .types.participant import SuggestArticlesResponse from .types.participant import SuggestFaqAnswersRequest from .types.participant import SuggestFaqAnswersResponse -from .types.participant import SuggestSmartRepliesRequest -from .types.participant import SuggestSmartRepliesResponse from .types.participant import Suggestion from .types.participant import SuggestionFeature from .types.participant import SuggestionResult +from .types.participant import SuggestSmartRepliesRequest +from .types.participant import SuggestSmartRepliesResponse from .types.participant import UpdateParticipantRequest from .types.session import DetectIntentRequest from .types.session import DetectIntentResponse @@ -200,12 +227,33 @@ 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", @@ -247,20 +295,24 @@ "CreateConversationRequest", "CreateDocumentRequest", "CreateEntityTypeRequest", + "CreateEnvironmentRequest", "CreateIntentRequest", "CreateKnowledgeBaseRequest", "CreateMessageRequest", "CreateParticipantRequest", "CreateSessionEntityTypeRequest", + "CreateVersionRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", "DeleteEntityTypeRequest", + "DeleteEnvironmentRequest", "DeleteIntentRequest", "DeleteKnowledgeBaseRequest", "DeleteSessionEntityTypeRequest", + "DeleteVersionRequest", "DetectIntentRequest", "DetectIntentResponse", "Document", @@ -270,11 +322,14 @@ "EntityTypeBatch", "EntityTypesClient", "Environment", + "EnvironmentHistory", "EnvironmentsClient", "EventInput", "ExportAgentRequest", "ExportAgentResponse", "FaqAnswer", + "Fulfillment", + "FulfillmentsClient", "GcsSource", "GcsSources", "GetAgentRequest", @@ -284,11 +339,15 @@ "GetConversationRequest", "GetDocumentRequest", "GetEntityTypeRequest", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", + "GetFulfillmentRequest", "GetIntentRequest", "GetKnowledgeBaseRequest", "GetParticipantRequest", "GetSessionEntityTypeRequest", "GetValidationResultRequest", + "GetVersionRequest", "HumanAgentAssistantConfig", "HumanAgentAssistantEvent", "HumanAgentHandoffConfig", @@ -303,6 +362,7 @@ "IntentsClient", "KnowledgeAnswers", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -330,6 +390,8 @@ "ListSessionEntityTypesResponse", "ListSuggestionsRequest", "ListSuggestionsResponse", + "ListVersionsRequest", + "ListVersionsResponse", "LoggingConfig", "Message", "MessageAnnotation", @@ -378,20 +440,25 @@ "TelephonyDtmf", "TelephonyDtmfEvents", "TextInput", + "TextToSpeechSettings", "TrainAgentRequest", "UpdateAnswerRecordRequest", "UpdateContextRequest", "UpdateConversationProfileRequest", "UpdateDocumentRequest", "UpdateEntityTypeRequest", + "UpdateEnvironmentRequest", + "UpdateFulfillmentRequest", "UpdateIntentRequest", "UpdateKnowledgeBaseRequest", "UpdateParticipantRequest", "UpdateSessionEntityTypeRequest", + "UpdateVersionRequest", "ValidationError", "ValidationResult", + "Version", + "VersionsClient", "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", ) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json b/google/cloud/dialogflow_v2beta1/gapic_metadata.json similarity index 100% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json rename to google/cloud/dialogflow_v2beta1/gapic_metadata.json diff --git a/google/cloud/dialogflow_v2beta1/services/__init__.py b/google/cloud/dialogflow_v2beta1/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/cloud/dialogflow_v2beta1/services/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/dialogflow_v2beta1/services/agents/__init__.py b/google/cloud/dialogflow_v2beta1/services/agents/__init__.py index 4bcbd7ac8..0501fa947 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AgentsClient from .async_client import AgentsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/agents/async_client.py b/google/cloud/dialogflow_v2beta1/services/agents/async_client.py index 3ec1c0c33..2be961279 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport from .client import AgentsClient @@ -54,29 +51,25 @@ class AgentsAsyncClient: agent_path = staticmethod(AgentsClient.agent_path) parse_agent_path = staticmethod(AgentsClient.parse_agent_path) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( AgentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AgentsClient.common_folder_path) parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) parse_common_organization_path = staticmethod( AgentsClient.parse_common_organization_path ) - common_project_path = staticmethod(AgentsClient.common_project_path) parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +84,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AgentsTransport: The transport used by the client instance. @@ -122,12 +115,12 @@ def transport(self) -> AgentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AgentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -190,7 +182,6 @@ async def get_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -226,7 +217,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -270,7 +260,6 @@ async def set_agent( This corresponds to the ``agent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -306,7 +295,6 @@ async def set_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -355,7 +343,6 @@ async def delete_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -376,7 +363,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -427,7 +413,6 @@ async def search_agents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -457,7 +442,6 @@ async def search_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -513,7 +497,6 @@ async def train_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -553,7 +536,6 @@ async def train_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -578,8 +560,8 @@ async def train_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -611,7 +593,6 @@ async def export_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -642,7 +623,6 @@ async def export_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -668,7 +648,7 @@ async def export_agent( response, self._client._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -705,7 +685,6 @@ async def import_agent( request (:class:`google.cloud.dialogflow_v2beta1.types.ImportAgentRequest`): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -732,7 +711,6 @@ async def import_agent( """ # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -756,8 +734,8 @@ async def import_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -792,7 +770,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest`): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -819,7 +796,6 @@ async def restore_agent( """ # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -843,8 +819,8 @@ async def restore_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -866,7 +842,6 @@ async def get_validation_result( request (:class:`google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest`): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -880,7 +855,6 @@ async def get_validation_result( """ # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2beta1/services/agents/client.py b/google/cloud/dialogflow_v2beta1/services/agents/client.py index 656adc907..78a33b6ec 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/client.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AgentsGrpcTransport from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class AgentsClientMeta(type): _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AgentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class AgentsClient(metaclass=AgentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,27 +153,28 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AgentsTransport: The transport used by the client instance. + AgentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/agent".format(project=project,) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match(r"^projects/(?P.+?)/agent$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -187,7 +187,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -198,7 +198,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -209,7 +209,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -220,7 +220,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -234,12 +234,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AgentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -294,9 +294,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -308,12 +309,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -328,8 +331,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -367,7 +370,6 @@ def get_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -405,10 +407,8 @@ def get_agent( # there are no flattened fields. if not isinstance(request, agent.GetAgentRequest): request = agent.GetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -448,7 +448,6 @@ def set_agent( This corresponds to the ``agent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -486,10 +485,8 @@ def set_agent( # there are no flattened fields. if not isinstance(request, gcd_agent.SetAgentRequest): request = gcd_agent.SetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -534,7 +531,6 @@ def delete_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -557,10 +553,8 @@ def delete_agent( # there are no flattened fields. if not isinstance(request, agent.DeleteAgentRequest): request = agent.DeleteAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -607,7 +601,6 @@ def search_agents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -639,10 +632,8 @@ def search_agents( # there are no flattened fields. if not isinstance(request, agent.SearchAgentsRequest): request = agent.SearchAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -694,7 +685,6 @@ def train_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -736,10 +726,8 @@ def train_agent( # there are no flattened fields. if not isinstance(request, agent.TrainAgentRequest): request = agent.TrainAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -760,8 +748,8 @@ def train_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -793,7 +781,6 @@ def export_agent( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -826,10 +813,8 @@ def export_agent( # there are no flattened fields. if not isinstance(request, agent.ExportAgentRequest): request = agent.ExportAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -851,7 +836,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -888,7 +873,6 @@ def import_agent( request (google.cloud.dialogflow_v2beta1.types.ImportAgentRequest): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -915,7 +899,6 @@ def import_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ImportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -940,8 +923,8 @@ def import_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -976,7 +959,6 @@ def restore_agent( request (google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1003,7 +985,6 @@ def restore_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.RestoreAgentRequest. # There's no risk of modifying the input as we've already verified @@ -1028,8 +1009,8 @@ def restore_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1051,7 +1032,6 @@ def get_validation_result( request (google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1065,7 +1045,6 @@ def get_validation_result( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.GetValidationResultRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2beta1/services/agents/pagers.py b/google/cloud/dialogflow_v2beta1/services/agents/pagers.py index e3c037634..e7d1795a3 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py index dfed91927..ceadcd3aa 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py index 7e10d2019..4dfac8794 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,6 +41,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -51,21 +61,24 @@ class AgentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -74,7 +87,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -88,29 +101,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -153,85 +213,78 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def get_agent( self, - ) -> typing.Callable[ - [agent.GetAgentRequest], - typing.Union[agent.Agent, typing.Awaitable[agent.Agent]], - ]: + ) -> Callable[[agent.GetAgentRequest], Union[agent.Agent, Awaitable[agent.Agent]]]: raise NotImplementedError() @property def set_agent( self, - ) -> typing.Callable[ - [gcd_agent.SetAgentRequest], - typing.Union[gcd_agent.Agent, typing.Awaitable[gcd_agent.Agent]], + ) -> Callable[ + [gcd_agent.SetAgentRequest], Union[gcd_agent.Agent, Awaitable[gcd_agent.Agent]] ]: raise NotImplementedError() @property def delete_agent( self, - ) -> typing.Callable[ - [agent.DeleteAgentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [agent.DeleteAgentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def search_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.SearchAgentsRequest], - typing.Union[ - agent.SearchAgentsResponse, typing.Awaitable[agent.SearchAgentsResponse] - ], + Union[agent.SearchAgentsResponse, Awaitable[agent.SearchAgentsResponse]], ]: raise NotImplementedError() @property def train_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.TrainAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def export_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ExportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def import_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ImportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def restore_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.RestoreAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def get_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetValidationResultRequest], - typing.Union[ + Union[ validation_result.ValidationResult, - typing.Awaitable[validation_result.ValidationResult], + Awaitable[validation_result.ValidationResult], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py index 675d3ac95..79926da48 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,9 +28,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -181,7 +179,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -291,7 +291,7 @@ def set_agent(self) -> Callable[[gcd_agent.SetAgentRequest], gcd_agent.Agent]: return self._stubs["set_agent"] @property - def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: + def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty_pb2.Empty]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -310,7 +310,7 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -346,7 +346,9 @@ def search_agents( return self._stubs["search_agents"] @property - def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operation]: + def train_agent( + self, + ) -> Callable[[agent.TrainAgentRequest], operations_pb2.Operation]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -368,14 +370,14 @@ def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operatio self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ExportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a ZIP file. @@ -397,14 +399,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ImportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -440,14 +442,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], operations.Operation]: + ) -> Callable[[agent.RestoreAgentRequest], operations_pb2.Operation]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a ZIP file. @@ -481,7 +483,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py index ad50f2638..f1e6cd4d1 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,9 +29,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO from .grpc import AgentsGrpcTransport @@ -59,7 +56,7 @@ class AgentsGrpcAsyncIOTransport(AgentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -301,7 +300,7 @@ def set_agent( @property def delete_agent( self, - ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -320,7 +319,7 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -358,7 +357,7 @@ def search_agents( @property def train_agent( self, - ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -380,14 +379,14 @@ def train_agent( self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a ZIP file. @@ -409,14 +408,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -452,14 +451,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a ZIP file. @@ -493,7 +492,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py b/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py index 7618f55a7..25960120e 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AnswerRecordsClient from .async_client import AnswerRecordsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py index 5e3908a60..45c8fd547 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport from .client import AnswerRecordsClient @@ -52,31 +49,26 @@ class AnswerRecordsAsyncClient: parse_answer_record_path = staticmethod( AnswerRecordsClient.parse_answer_record_path ) - common_billing_account_path = staticmethod( AnswerRecordsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AnswerRecordsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) parse_common_folder_path = staticmethod( AnswerRecordsClient.parse_common_folder_path ) - common_organization_path = staticmethod( AnswerRecordsClient.common_organization_path ) parse_common_organization_path = staticmethod( AnswerRecordsClient.parse_common_organization_path ) - common_project_path = staticmethod(AnswerRecordsClient.common_project_path) parse_common_project_path = staticmethod( AnswerRecordsClient.parse_common_project_path ) - common_location_path = staticmethod(AnswerRecordsClient.common_location_path) parse_common_location_path = staticmethod( AnswerRecordsClient.parse_common_location_path @@ -84,7 +76,8 @@ class AnswerRecordsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AnswerRecordsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AnswerRecordsTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> AnswerRecordsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the answer records client. + """Instantiates the answer records client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AnswerRecordsClient( credentials=credentials, transport=transport, @@ -190,7 +182,6 @@ async def get_answer_record( request (:class:`google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest`): The request object. Request message for [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -227,16 +218,14 @@ async def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. - request = answer_record.GetAnswerRecordRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -283,7 +272,6 @@ async def list_answer_records( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -293,7 +281,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -313,7 +301,6 @@ async def list_answer_records( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -348,7 +335,7 @@ async def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -371,7 +358,6 @@ async def update_answer_record( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -408,12 +394,11 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -430,7 +415,6 @@ async def update_answer_record( # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/client.py index a0cceb54b..d37a08d01 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AnswerRecordsGrpcTransport from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class AnswerRecordsClientMeta(type): _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AnswerRecordsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,23 +149,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AnswerRecordsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AnswerRecordsTransport: The transport used by the client instance. + AnswerRecordsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def answer_record_path(project: str, answer_record: str,) -> str: - """Return a fully-qualified answer_record string.""" + """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]: - """Parse a answer_record path into its component segments.""" + """Parses a answer_record path into its component segments.""" m = re.match( r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path ) @@ -174,7 +174,7 @@ def parse_answer_record_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -187,7 +187,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -198,7 +198,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -209,7 +209,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -220,7 +220,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -234,12 +234,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AnswerRecordsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the answer records client. + """Instantiates the answer records client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -294,9 +294,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -308,12 +309,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -328,8 +331,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -359,7 +362,6 @@ def get_answer_record( request (google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest): The request object. Request message for [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -396,16 +398,14 @@ def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a answer_record.GetAnswerRecordRequest. # There's no risk of modifying the input as we've already verified @@ -453,7 +453,6 @@ def list_answer_records( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -463,7 +462,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -485,10 +484,8 @@ def list_answer_records( # there are no flattened fields. if not isinstance(request, answer_record.ListAnswerRecordsRequest): request = answer_record.ListAnswerRecordsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -519,7 +516,7 @@ def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -542,7 +539,6 @@ def update_answer_record( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -579,12 +575,11 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -603,10 +598,8 @@ def update_answer_record( # there are no flattened fields. if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): request = gcd_answer_record.UpdateAnswerRecordRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py b/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py index 1b0e3ba56..777fb93c6 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py index bbb65cf15..e97f4f57d 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py index 1fb664a96..bd8dbeb96 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AnswerRecordsTransport(abc.ABC): """Abstract transport class for AnswerRecords.""" @@ -47,21 +57,24 @@ class AnswerRecordsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -126,22 +186,20 @@ def _prep_wrapped_messages(self, client_info): @property def get_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.GetAnswerRecordRequest], - typing.Union[ - answer_record.AnswerRecord, typing.Awaitable[answer_record.AnswerRecord] - ], + Union[answer_record.AnswerRecord, Awaitable[answer_record.AnswerRecord]], ]: raise NotImplementedError() @property def list_answer_records( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.ListAnswerRecordsRequest], - typing.Union[ + Union[ answer_record.ListAnswerRecordsResponse, - typing.Awaitable[answer_record.ListAnswerRecordsResponse], + Awaitable[answer_record.ListAnswerRecordsResponse], ], ]: raise NotImplementedError() @@ -149,11 +207,10 @@ def list_answer_records( @property def update_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_answer_record.UpdateAnswerRecordRequest], - typing.Union[ - gcd_answer_record.AnswerRecord, - typing.Awaitable[gcd_answer_record.AnswerRecord], + Union[ + gcd_answer_record.AnswerRecord, Awaitable[gcd_answer_record.AnswerRecord] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py index 19901a8f3..ec23c6543 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py index a0e18f180..79aab5785 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .grpc import AnswerRecordsGrpcTransport @@ -55,7 +52,7 @@ class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py b/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py index 56b19b0f2..4c5791dcf 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ContextsClient from .async_client import ContextsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py b/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py index 5aceb21ee..775dc4f81 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport from .client import ContextsClient @@ -51,31 +48,27 @@ class ContextsAsyncClient: context_path = staticmethod(ContextsClient.context_path) parse_context_path = staticmethod(ContextsClient.parse_context_path) - common_billing_account_path = staticmethod( ContextsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ContextsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ContextsClient.common_folder_path) parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) - common_organization_path = staticmethod(ContextsClient.common_organization_path) parse_common_organization_path = staticmethod( ContextsClient.parse_common_organization_path ) - common_project_path = staticmethod(ContextsClient.common_project_path) parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) - common_location_path = staticmethod(ContextsClient.common_location_path) parse_common_location_path = staticmethod(ContextsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +83,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -107,7 +100,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ContextsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ContextsTransport: The transport used by the client instance. @@ -121,12 +114,12 @@ def transport(self) -> ContextsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ContextsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the contexts client. + """Instantiates the contexts client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -158,7 +151,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ContextsClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def list_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -229,7 +220,6 @@ async def list_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -290,7 +280,6 @@ async def get_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -334,7 +323,6 @@ async def get_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -398,7 +386,6 @@ async def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -442,7 +429,6 @@ async def create_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -473,7 +459,7 @@ async def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -496,7 +482,6 @@ async def update_context( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -540,7 +525,6 @@ async def update_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -600,7 +584,6 @@ async def delete_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -621,7 +604,6 @@ async def delete_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -676,7 +658,6 @@ async def delete_all_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -697,7 +678,6 @@ async def delete_all_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/client.py b/google/cloud/dialogflow_v2beta1/services/contexts/client.py index 08291572e..d9b7ba996 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/client.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,9 +33,8 @@ from google.cloud.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ContextsGrpcTransport from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ContextsClientMeta(type): _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ContextsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ContextsClient(metaclass=ContextsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ContextsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ContextsTransport: The transport used by the client instance. + ContextsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -176,7 +176,7 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -189,7 +189,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -200,7 +200,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -211,7 +211,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -222,7 +222,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -236,12 +236,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ContextsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the contexts client. + """Instantiates the contexts client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -296,9 +296,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -310,12 +311,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -330,8 +333,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -379,7 +382,6 @@ def list_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -411,10 +413,8 @@ def list_contexts( # there are no flattened fields. if not isinstance(request, context.ListContextsRequest): request = context.ListContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -471,7 +471,6 @@ def get_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -517,10 +516,8 @@ def get_context( # there are no flattened fields. if not isinstance(request, context.GetContextRequest): request = context.GetContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -580,7 +577,6 @@ def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -626,10 +622,8 @@ def create_context( # there are no flattened fields. if not isinstance(request, gcd_context.CreateContextRequest): request = gcd_context.CreateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -656,7 +650,7 @@ def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -679,7 +673,6 @@ def update_context( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -725,10 +718,8 @@ def update_context( # there are no flattened fields. if not isinstance(request, gcd_context.UpdateContextRequest): request = gcd_context.UpdateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -784,7 +775,6 @@ def delete_context( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -807,10 +797,8 @@ def delete_context( # there are no flattened fields. if not isinstance(request, context.DeleteContextRequest): request = context.DeleteContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -861,7 +849,6 @@ def delete_all_contexts( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -884,10 +871,8 @@ def delete_all_contexts( # there are no flattened fields. if not isinstance(request, context.DeleteAllContextsRequest): request = context.DeleteAllContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py b/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py index 9460cfd11..d09d4bb51 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py index 7437034e4..d25eca3aa 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py index 1d3b4783b..90b09437a 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ContextsTransport(abc.ABC): """Abstract transport class for Contexts.""" @@ -48,21 +58,24 @@ class ContextsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -134,56 +194,53 @@ def _prep_wrapped_messages(self, client_info): @property def list_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.ListContextsRequest], - typing.Union[ - context.ListContextsResponse, typing.Awaitable[context.ListContextsResponse] - ], + Union[context.ListContextsResponse, Awaitable[context.ListContextsResponse]], ]: raise NotImplementedError() @property def get_context( self, - ) -> typing.Callable[ - [context.GetContextRequest], - typing.Union[context.Context, typing.Awaitable[context.Context]], + ) -> Callable[ + [context.GetContextRequest], Union[context.Context, Awaitable[context.Context]] ]: raise NotImplementedError() @property def create_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.CreateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def update_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.UpdateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def delete_context( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteContextRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def delete_all_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteAllContextsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py index ae75375c9..393d76c3a 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -330,7 +330,9 @@ def update_context( return self._stubs["update_context"] @property - def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty]: + def delete_context( + self, + ) -> Callable[[context.DeleteContextRequest], empty_pb2.Empty]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -349,14 +351,14 @@ def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], empty.Empty]: + ) -> Callable[[context.DeleteAllContextsRequest], empty_pb2.Empty]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -375,7 +377,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py index 3e2d8fdfb..d1a479ef5 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO from .grpc import ContextsGrpcTransport @@ -56,7 +53,7 @@ class ContextsGrpcAsyncIOTransport(ContextsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -340,7 +339,7 @@ def update_context( @property def delete_context( self, - ) -> Callable[[context.DeleteContextRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteContextRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -359,14 +358,14 @@ def delete_context( self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -385,7 +384,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py index 9ab8de0b8..c0cb1cd03 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ConversationProfilesClient from .async_client import ConversationProfilesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py index a052858ff..53bba6cca 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport from .client import ConversationProfilesClient @@ -54,6 +51,12 @@ class ConversationProfilesAsyncClient: agent_path = staticmethod(ConversationProfilesClient.agent_path) parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod( + ConversationProfilesClient.conversation_model_path + ) + parse_conversation_model_path = staticmethod( + ConversationProfilesClient.parse_conversation_model_path + ) conversation_profile_path = staticmethod( ConversationProfilesClient.conversation_profile_path ) @@ -66,31 +69,26 @@ class ConversationProfilesAsyncClient: parse_knowledge_base_path = staticmethod( ConversationProfilesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( ConversationProfilesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationProfilesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationProfilesClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationProfilesClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationProfilesClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationProfilesClient.common_project_path) parse_common_project_path = staticmethod( ConversationProfilesClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationProfilesClient.common_location_path) parse_common_location_path = staticmethod( ConversationProfilesClient.parse_common_location_path @@ -98,7 +96,8 @@ class ConversationProfilesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -113,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -130,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationProfilesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ConversationProfilesTransport: The transport used by the client instance. @@ -145,12 +144,12 @@ def transport(self) -> ConversationProfilesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversation profiles client. + """Instantiates the conversation profiles client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -182,7 +181,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationProfilesClient( credentials=credentials, transport=transport, @@ -214,7 +212,6 @@ async def list_conversation_profiles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -244,7 +241,6 @@ async def list_conversation_profiles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -297,7 +293,6 @@ async def get_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -324,7 +319,6 @@ async def get_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -385,7 +379,6 @@ async def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,7 +405,6 @@ async def create_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -443,7 +435,7 @@ async def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -474,7 +466,6 @@ async def update_conversation_profile( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -501,7 +492,6 @@ async def update_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -554,7 +544,6 @@ async def delete_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -575,7 +564,6 @@ async def delete_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py index 3e4c17399..63826064f 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationProfilesGrpcTransport from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class ConversationProfilesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[ConversationProfilesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,34 +157,53 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationProfilesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ConversationProfilesTransport: The transport used by the client instance. + ConversationProfilesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/agent".format(project=project,) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match(r"^projects/(?P.+?)/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: - """Return a fully-qualified conversation_profile string.""" + """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]: - """Parse a conversation_profile path into its component segments.""" + """Parses a conversation_profile path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path, @@ -194,14 +212,14 @@ def parse_conversation_profile_path(path: str) -> Dict[str, str]: @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -210,14 +228,14 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def knowledge_base_path(project: str, knowledge_base: str,) -> str: - """Return a fully-qualified knowledge_base string.""" + """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]: - """Parse a knowledge_base path into its component segments.""" + """Parses a knowledge_base path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path ) @@ -225,7 +243,7 @@ def parse_knowledge_base_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -238,7 +256,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -249,7 +267,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -260,7 +278,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -271,7 +289,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -285,12 +303,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ConversationProfilesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversation profiles client. + """Instantiates the conversation profiles client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -345,9 +363,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -359,12 +378,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -379,8 +400,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -419,7 +440,6 @@ def list_conversation_profiles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -453,10 +473,8 @@ def list_conversation_profiles( request, conversation_profile.ListConversationProfilesRequest ): request = conversation_profile.ListConversationProfilesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -507,7 +525,6 @@ def get_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -536,10 +553,8 @@ def get_conversation_profile( # there are no flattened fields. if not isinstance(request, conversation_profile.GetConversationProfileRequest): request = conversation_profile.GetConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -596,7 +611,6 @@ def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -627,10 +641,8 @@ def create_conversation_profile( request, gcd_conversation_profile.CreateConversationProfileRequest ): request = gcd_conversation_profile.CreateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -659,7 +671,7 @@ def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -690,7 +702,6 @@ def update_conversation_profile( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -721,10 +732,8 @@ def update_conversation_profile( request, gcd_conversation_profile.UpdateConversationProfileRequest ): request = gcd_conversation_profile.UpdateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -775,7 +784,6 @@ def delete_conversation_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -800,10 +808,8 @@ def delete_conversation_profile( request, conversation_profile.DeleteConversationProfileRequest ): request = conversation_profile.DeleteConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py index 1e03482d0..e9679190a 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py index e97774bcf..f2a4e2203 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py index a7f357435..13c13fb36 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import conversation_profile from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ConversationProfilesTransport(abc.ABC): """Abstract transport class for ConversationProfiles.""" @@ -50,21 +60,24 @@ class ConversationProfilesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_conversation_profiles( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.ListConversationProfilesRequest], - typing.Union[ + Union[ conversation_profile.ListConversationProfilesResponse, - typing.Awaitable[conversation_profile.ListConversationProfilesResponse], + Awaitable[conversation_profile.ListConversationProfilesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_conversation_profiles( @property def get_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.GetConversationProfileRequest], - typing.Union[ + Union[ conversation_profile.ConversationProfile, - typing.Awaitable[conversation_profile.ConversationProfile], + Awaitable[conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_conversation_profile( @property def create_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.CreateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_conversation_profile( @property def update_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.UpdateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.DeleteConversationProfileRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py index 80cd9e78f..4641c6bfb 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,8 +28,7 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -358,7 +358,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> Callable[[conversation_profile.DeleteConversationProfileRequest], empty.Empty]: + ) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete conversation profile method over gRPC. Deletes the specified conversation profile. @@ -377,7 +379,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py index 72244a461..4bb6d208b 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,8 +29,7 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationProfilesGrpcTransport @@ -58,7 +55,7 @@ class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -363,7 +362,8 @@ def update_conversation_profile( def delete_conversation_profile( self, ) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], Awaitable[empty.Empty] + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete conversation profile method over gRPC. @@ -383,7 +383,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py index cce809abe..f6f6b90ff 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ConversationsClient from .async_client import ConversationsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py b/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py index cf4fb1475..37a293a49 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.conversations import pagers from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport from .client import ConversationsClient @@ -59,31 +56,26 @@ class ConversationsAsyncClient: ) message_path = staticmethod(ConversationsClient.message_path) parse_message_path = staticmethod(ConversationsClient.parse_message_path) - common_billing_account_path = staticmethod( ConversationsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationsClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationsClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationsClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationsClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationsClient.common_project_path) parse_common_project_path = staticmethod( ConversationsClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationsClient.common_location_path) parse_common_location_path = staticmethod( ConversationsClient.parse_common_location_path @@ -91,7 +83,8 @@ class ConversationsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -106,7 +99,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -123,7 +116,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ConversationsTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> ConversationsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversations client. + """Instantiates the conversations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationsClient( credentials=credentials, transport=transport, @@ -231,7 +223,6 @@ async def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -263,7 +254,6 @@ async def create_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -313,7 +303,6 @@ async def list_conversations( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -323,7 +312,7 @@ async def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -343,7 +332,6 @@ async def list_conversations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -395,7 +383,6 @@ async def get_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,7 +414,6 @@ async def get_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -476,7 +462,6 @@ async def complete_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -508,7 +493,6 @@ async def complete_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -557,7 +541,6 @@ async def batch_create_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -584,7 +567,6 @@ async def batch_create_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -635,7 +617,6 @@ async def list_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -645,7 +626,7 @@ async def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. @@ -665,7 +646,6 @@ async def list_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/client.py b/google/cloud/dialogflow_v2beta1/services/conversations/client.py index 5dee0325f..675bf4480 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationsGrpcTransport from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ConversationsClientMeta(type): _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ConversationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ConversationsClient(metaclass=ConversationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ConversationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ConversationsTransport: The transport used by the client instance. + ConversationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def conversation_path(project: str, conversation: str,) -> str: - """Return a fully-qualified conversation string.""" + """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]: - """Parse a conversation path into its component segments.""" + """Parses a conversation path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)$", path ) @@ -175,14 +175,14 @@ def parse_conversation_path(path: str) -> Dict[str, str]: @staticmethod def conversation_profile_path(project: str, conversation_profile: str,) -> str: - """Return a fully-qualified conversation_profile string.""" + """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]: - """Parse a conversation_profile path into its component segments.""" + """Parses a conversation_profile path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path, @@ -191,14 +191,14 @@ def parse_conversation_profile_path(path: str) -> Dict[str, str]: @staticmethod def message_path(project: str, conversation: str, message: str,) -> str: - """Return a fully-qualified message string.""" + """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]: - """Parse a message path into its component segments.""" + """Parses a message path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path, @@ -207,7 +207,7 @@ def parse_message_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -220,7 +220,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -231,7 +231,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -242,7 +242,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -253,7 +253,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -267,12 +267,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ConversationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the conversations client. + """Instantiates the conversations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -327,9 +327,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -341,12 +342,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -361,8 +364,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -426,7 +429,6 @@ def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -460,10 +462,8 @@ def create_conversation( # there are no flattened fields. if not isinstance(request, gcd_conversation.CreateConversationRequest): request = gcd_conversation.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -509,7 +509,6 @@ def list_conversations( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -519,7 +518,7 @@ def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -541,10 +540,8 @@ def list_conversations( # there are no flattened fields. if not isinstance(request, conversation.ListConversationsRequest): request = conversation.ListConversationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -592,7 +589,6 @@ def get_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -626,10 +622,8 @@ def get_conversation( # there are no flattened fields. if not isinstance(request, conversation.GetConversationRequest): request = conversation.GetConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -674,7 +668,6 @@ def complete_conversation( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -708,10 +701,8 @@ def complete_conversation( # there are no flattened fields. if not isinstance(request, conversation.CompleteConversationRequest): request = conversation.CompleteConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -756,7 +747,6 @@ def batch_create_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -785,10 +775,8 @@ def batch_create_messages( # there are no flattened fields. if not isinstance(request, conversation.BatchCreateMessagesRequest): request = conversation.BatchCreateMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -835,7 +823,6 @@ def list_messages( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -845,7 +832,7 @@ def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. @@ -867,10 +854,8 @@ def list_messages( # there are no flattened fields. if not isinstance(request, conversation.ListMessagesRequest): request = conversation.ListMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py b/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py index f9a2ca203..abde5304e 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py index 6597b6d01..2989914f7 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py index ecc38991b..47f6e70ae 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ConversationsTransport(abc.ABC): """Abstract transport class for Conversations.""" @@ -47,21 +57,24 @@ class ConversationsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -137,23 +197,20 @@ def _prep_wrapped_messages(self, client_info): @property def create_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation.CreateConversationRequest], - typing.Union[ - gcd_conversation.Conversation, - typing.Awaitable[gcd_conversation.Conversation], - ], + Union[gcd_conversation.Conversation, Awaitable[gcd_conversation.Conversation]], ]: raise NotImplementedError() @property def list_conversations( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListConversationsRequest], - typing.Union[ + Union[ conversation.ListConversationsResponse, - typing.Awaitable[conversation.ListConversationsResponse], + Awaitable[conversation.ListConversationsResponse], ], ]: raise NotImplementedError() @@ -161,33 +218,29 @@ def list_conversations( @property def get_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.GetConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def complete_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.CompleteConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def batch_create_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.BatchCreateMessagesRequest], - typing.Union[ + Union[ conversation.BatchCreateMessagesResponse, - typing.Awaitable[conversation.BatchCreateMessagesResponse], + Awaitable[conversation.BatchCreateMessagesResponse], ], ]: raise NotImplementedError() @@ -195,11 +248,11 @@ def batch_create_messages( @property def list_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListMessagesRequest], - typing.Union[ + Union[ conversation.ListMessagesResponse, - typing.Awaitable[conversation.ListMessagesResponse], + Awaitable[conversation.ListMessagesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py index c0f5c981a..c61488ce1 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py index a00f0288d..9502a95c4 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -55,7 +52,7 @@ class ConversationsGrpcAsyncIOTransport(ConversationsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2beta1/services/documents/__init__.py b/google/cloud/dialogflow_v2beta1/services/documents/__init__.py index 5f6db6815..f610c36b0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DocumentsClient from .async_client import DocumentsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/documents/async_client.py b/google/cloud/dialogflow_v2beta1/services/documents/async_client.py index 391764994..9a02c9097 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport from .client import DocumentsClient @@ -54,25 +51,20 @@ class DocumentsAsyncClient: document_path = staticmethod(DocumentsClient.document_path) parse_document_path = staticmethod(DocumentsClient.parse_document_path) - common_billing_account_path = staticmethod( DocumentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( DocumentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DocumentsClient.common_folder_path) parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentsClient.common_organization_path) parse_common_organization_path = staticmethod( DocumentsClient.parse_common_organization_path ) - common_project_path = staticmethod(DocumentsClient.common_project_path) parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) - common_location_path = staticmethod(DocumentsClient.common_location_path) parse_common_location_path = staticmethod( DocumentsClient.parse_common_location_path @@ -80,7 +72,8 @@ class DocumentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DocumentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: DocumentsTransport: The transport used by the client instance. @@ -126,12 +119,12 @@ def transport(self) -> DocumentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DocumentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the documents client. + """Instantiates the documents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DocumentsClient( credentials=credentials, transport=transport, @@ -197,7 +189,6 @@ async def list_documents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -227,7 +218,6 @@ async def list_documents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -282,7 +272,6 @@ async def get_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -316,7 +305,6 @@ async def get_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -372,7 +360,6 @@ async def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -410,7 +397,6 @@ async def create_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -453,13 +439,14 @@ async def import_documents( metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Args: request (:class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest`): The request object. Request message for [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -477,7 +464,6 @@ async def import_documents( """ # Create or coerce a protobuf request object. - request = document.ImportDocumentsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -533,7 +519,6 @@ async def delete_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -573,7 +558,6 @@ async def delete_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -598,7 +582,7 @@ async def delete_document( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -610,7 +594,7 @@ async def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -637,7 +621,6 @@ async def update_document( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -675,7 +658,6 @@ async def update_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -754,7 +736,6 @@ async def reload_document( This corresponds to the ``gcs_source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -792,7 +773,6 @@ async def reload_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if gcs_source is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/documents/client.py b/google/cloud/dialogflow_v2beta1/services/documents/client.py index a7890ee89..6fde14c5f 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/client.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DocumentsGrpcTransport from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class DocumentsClientMeta(type): _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[DocumentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class DocumentsClient(metaclass=DocumentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DocumentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DocumentsTransport: The transport used by the client instance. + DocumentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -179,7 +179,7 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -192,7 +192,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -203,7 +203,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -214,7 +214,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -225,7 +225,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -239,12 +239,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DocumentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the documents client. + """Instantiates the documents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -299,9 +299,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -313,12 +314,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -333,8 +336,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -375,7 +378,6 @@ def list_documents( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -407,10 +409,8 @@ def list_documents( # there are no flattened fields. if not isinstance(request, document.ListDocumentsRequest): request = document.ListDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -461,7 +461,6 @@ def get_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -497,10 +496,8 @@ def get_document( # there are no flattened fields. if not isinstance(request, document.GetDocumentRequest): request = document.GetDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -552,7 +549,6 @@ def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -592,10 +588,8 @@ def create_document( # there are no flattened fields. if not isinstance(request, gcd_document.CreateDocumentRequest): request = gcd_document.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -634,13 +628,14 @@ def import_documents( metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Args: request (google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest): The request object. Request message for [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -658,7 +653,6 @@ def import_documents( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a document.ImportDocumentsRequest. # There's no risk of modifying the input as we've already verified @@ -715,7 +709,6 @@ def delete_document( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -757,10 +750,8 @@ def delete_document( # there are no flattened fields. if not isinstance(request, document.DeleteDocumentRequest): request = document.DeleteDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -781,7 +772,7 @@ def delete_document( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -793,7 +784,7 @@ def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -820,7 +811,6 @@ def update_document( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -860,10 +850,8 @@ def update_document( # there are no flattened fields. if not isinstance(request, gcd_document.UpdateDocumentRequest): request = gcd_document.UpdateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -938,7 +926,6 @@ def reload_document( This corresponds to the ``gcs_source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -978,10 +965,8 @@ def reload_document( # there are no flattened fields. if not isinstance(request, document.ReloadDocumentRequest): request = document.ReloadDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if gcs_source is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/documents/pagers.py b/google/cloud/dialogflow_v2beta1/services/documents/pagers.py index 9169210c7..35afd5c3f 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py index af02ba19c..5d4948aa0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py index 352d60dce..992198722 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class DocumentsTransport(abc.ABC): """Abstract transport class for Documents.""" @@ -49,21 +59,24 @@ class DocumentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -72,7 +85,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -143,11 +203,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ListDocumentsRequest], - typing.Union[ - document.ListDocumentsResponse, - typing.Awaitable[document.ListDocumentsResponse], + Union[ + document.ListDocumentsResponse, Awaitable[document.ListDocumentsResponse] ], ]: raise NotImplementedError() @@ -155,54 +214,54 @@ def list_documents( @property def get_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.GetDocumentRequest], - typing.Union[document.Document, typing.Awaitable[document.Document]], + Union[document.Document, Awaitable[document.Document]], ]: raise NotImplementedError() @property def create_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.CreateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def import_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ImportDocumentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.DeleteDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.UpdateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def reload_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ReloadDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py index 11c7488ee..822acc7f0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -301,7 +301,7 @@ def get_document( @property def create_document( self, - ) -> Callable[[gcd_document.CreateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.CreateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the create document method over gRPC. Creates a new document. @@ -323,18 +323,20 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def import_documents( self, - ) -> Callable[[document.ImportDocumentsRequest], operations.Operation]: + ) -> Callable[[document.ImportDocumentsRequest], operations_pb2.Operation]: r"""Return a callable for the import documents method over gRPC. Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Returns: Callable[[~.ImportDocumentsRequest], @@ -350,14 +352,14 @@ def import_documents( self._stubs["import_documents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments", request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_documents"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], operations.Operation]: + ) -> Callable[[document.DeleteDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -379,14 +381,14 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @property def update_document( self, - ) -> Callable[[gcd_document.UpdateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.UpdateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the update document method over gRPC. Updates the specified document. @@ -408,14 +410,14 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], operations.Operation]: + ) -> Callable[[document.ReloadDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -445,7 +447,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py index 112d72a50..56968f9fc 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO from .grpc import DocumentsGrpcTransport @@ -57,7 +54,7 @@ class DocumentsGrpcAsyncIOTransport(DocumentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -310,7 +309,7 @@ def get_document( def create_document( self, ) -> Callable[ - [gcd_document.CreateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.CreateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create document method over gRPC. @@ -333,18 +332,22 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def import_documents( self, - ) -> Callable[[document.ImportDocumentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ImportDocumentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the import documents method over gRPC. Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Returns: Callable[[~.ImportDocumentsRequest], @@ -360,14 +363,16 @@ def import_documents( self._stubs["import_documents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments", request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_documents"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.DeleteDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -389,7 +394,7 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @@ -397,7 +402,7 @@ def delete_document( def update_document( self, ) -> Callable[ - [gcd_document.UpdateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.UpdateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update document method over gRPC. @@ -420,14 +425,16 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ReloadDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -457,7 +464,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py b/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py index f52849c66..77cd53e9c 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EntityTypesClient from .async_client import EntityTypesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py b/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py index 8c323260b..b3986524a 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,10 +31,9 @@ from google.cloud.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -54,27 +51,22 @@ class EntityTypesAsyncClient: entity_type_path = staticmethod(EntityTypesClient.entity_type_path) parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) - common_billing_account_path = staticmethod( EntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) - common_organization_path = staticmethod(EntityTypesClient.common_organization_path) parse_common_organization_path = staticmethod( EntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(EntityTypesClient.common_project_path) parse_common_project_path = staticmethod( EntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(EntityTypesClient.common_location_path) parse_common_location_path = staticmethod( EntityTypesClient.parse_common_location_path @@ -82,7 +74,8 @@ class EntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +90,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -114,7 +107,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EntityTypesTransport: The transport used by the client instance. @@ -128,12 +121,12 @@ def transport(self) -> EntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -165,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -210,7 +202,6 @@ async def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -240,7 +231,6 @@ async def list_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -308,7 +298,6 @@ async def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -348,7 +337,6 @@ async def get_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -416,7 +404,6 @@ async def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -456,7 +443,6 @@ async def create_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -490,7 +476,7 @@ async def update_entity_type( *, entity_type: gcd_entity_type.EntityType = None, language_code: str = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -523,7 +509,6 @@ async def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -563,7 +548,6 @@ async def update_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if language_code is not None: @@ -618,7 +602,6 @@ async def delete_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -639,7 +622,6 @@ async def delete_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -678,7 +660,6 @@ async def batch_update_entity_types( request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest`): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -696,7 +677,6 @@ async def batch_update_entity_types( """ # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -721,7 +701,7 @@ async def batch_update_entity_types( response, self._client._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -761,7 +741,6 @@ async def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -801,10 +780,8 @@ async def batch_delete_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if entity_type_names: request.entity_type_names.extend(entity_type_names) @@ -829,8 +806,8 @@ async def batch_delete_entity_types( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -881,7 +858,6 @@ async def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -921,12 +897,10 @@ async def batch_create_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -951,8 +925,8 @@ async def batch_create_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1007,7 +981,6 @@ async def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1047,12 +1020,10 @@ async def batch_update_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -1077,8 +1048,8 @@ async def batch_update_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1132,7 +1103,6 @@ async def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1172,12 +1142,10 @@ async def batch_delete_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entity_values: request.entity_values.extend(entity_values) @@ -1202,8 +1170,8 @@ async def batch_delete_entities( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/client.py b/google/cloud/dialogflow_v2beta1/services/entity_types/client.py index 32b206474..2981f771d 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/client.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,10 +35,9 @@ from google.cloud.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class EntityTypesClientMeta(type): _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class EntityTypesClient(metaclass=EntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EntityTypesTransport: The transport used by the client instance. + EntityTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def entity_type_path(project: str, entity_type: str,) -> str: - """Return a fully-qualified entity_type string.""" + """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]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/entityTypes/(?P.+?)$", path ) @@ -178,7 +178,7 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -191,7 +191,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -224,7 +224,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -238,12 +238,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -298,9 +298,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -312,12 +313,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -332,8 +335,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -385,7 +388,6 @@ def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,10 +419,8 @@ def list_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.ListEntityTypesRequest): request = entity_type.ListEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -484,7 +484,6 @@ def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -526,10 +525,8 @@ def get_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.GetEntityTypeRequest): request = entity_type.GetEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -593,7 +590,6 @@ def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -635,10 +631,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): request = gcd_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -668,7 +662,7 @@ def update_entity_type( *, entity_type: gcd_entity_type.EntityType = None, language_code: str = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -701,7 +695,6 @@ def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -743,10 +736,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): request = gcd_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if language_code is not None: @@ -797,7 +788,6 @@ def delete_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -820,10 +810,8 @@ def delete_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.DeleteEntityTypeRequest): request = entity_type.DeleteEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -858,7 +846,6 @@ def batch_update_entity_types( request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -876,7 +863,6 @@ def batch_update_entity_types( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a entity_type.BatchUpdateEntityTypesRequest. # There's no risk of modifying the input as we've already verified @@ -904,7 +890,7 @@ def batch_update_entity_types( response, self._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -944,7 +930,6 @@ def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -986,10 +971,8 @@ def batch_delete_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): request = entity_type.BatchDeleteEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type_names is not None: @@ -1014,8 +997,8 @@ def batch_delete_entity_types( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1066,7 +1049,6 @@ def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1108,10 +1090,8 @@ def batch_create_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchCreateEntitiesRequest): request = entity_type.BatchCreateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1136,8 +1116,8 @@ def batch_create_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1192,7 +1172,6 @@ def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1234,10 +1213,8 @@ def batch_update_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): request = entity_type.BatchUpdateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1262,8 +1239,8 @@ def batch_update_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1317,7 +1294,6 @@ def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1359,10 +1335,8 @@ def batch_delete_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): request = entity_type.BatchDeleteEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_values is not None: @@ -1387,8 +1361,8 @@ def batch_delete_entities( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py b/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py index 06d3999b4..d5b513263 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py index 963959d1a..07ea82e1b 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py index 3b3c283cd..90ab77975 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -50,21 +60,24 @@ class EntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -163,11 +223,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.ListEntityTypesRequest], - typing.Union[ + Union[ entity_type.ListEntityTypesResponse, - typing.Awaitable[entity_type.ListEntityTypesResponse], + Awaitable[entity_type.ListEntityTypesResponse], ], ]: raise NotImplementedError() @@ -175,85 +235,81 @@ def list_entity_types( @property def get_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.GetEntityTypeRequest], - typing.Union[entity_type.EntityType, typing.Awaitable[entity_type.EntityType]], + Union[entity_type.EntityType, Awaitable[entity_type.EntityType]], ]: raise NotImplementedError() @property def create_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def delete_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.DeleteEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def batch_update_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_create_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchCreateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_update_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py index 3cd835d14..f85284d34 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +355,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty.Empty]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty_pb2.Empty]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -374,14 +374,16 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] @property def batch_update_entity_types( self, - ) -> Callable[[entity_type.BatchUpdateEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch update entity types method over gRPC. Updates/Creates multiple entity types in the specified agent. @@ -402,14 +404,16 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @property def batch_delete_entity_types( self, - ) -> Callable[[entity_type.BatchDeleteEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch delete entity types method over gRPC. Deletes entity types in the specified agent. Operation @@ -429,14 +433,14 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @property def batch_create_entities( self, - ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch create entities method over gRPC. Creates multiple new entities in the specified entity type. @@ -458,14 +462,14 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @property def batch_update_entities( self, - ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch update entities method over gRPC. Updates or creates multiple entities in the specified entity @@ -489,14 +493,14 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @property def batch_delete_entities( self, - ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete entities method over gRPC. Deletes entities in the specified entity type. @@ -518,7 +522,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py index c4f4439fd..7c698f704 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -58,7 +55,7 @@ class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -364,7 +363,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty.Empty]]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -383,7 +382,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] @@ -391,7 +390,7 @@ def delete_entity_type( def batch_update_entity_types( self, ) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entity types method over gRPC. @@ -413,7 +412,7 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @@ -421,7 +420,7 @@ def batch_update_entity_types( def batch_delete_entity_types( self, ) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entity types method over gRPC. @@ -442,7 +441,7 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @@ -450,7 +449,7 @@ def batch_delete_entity_types( def batch_create_entities( self, ) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchCreateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch create entities method over gRPC. @@ -473,7 +472,7 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @@ -481,7 +480,7 @@ def batch_create_entities( def batch_update_entities( self, ) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entities method over gRPC. @@ -506,7 +505,7 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @@ -514,7 +513,7 @@ def batch_update_entities( def batch_delete_entities( self, ) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entities method over gRPC. @@ -537,7 +536,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2beta1/services/environments/__init__.py b/google/cloud/dialogflow_v2beta1/services/environments/__init__.py index a67f2316d..0c2be9484 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EnvironmentsClient from .async_client import EnvironmentsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/environments/async_client.py b/google/cloud/dialogflow_v2beta1/services/environments/async_client.py index 232e39ebf..c6e36ef4a 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,15 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.types import environment - +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport from .client import EnvironmentsClient @@ -48,27 +47,24 @@ class EnvironmentsAsyncClient: environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_path) common_billing_account_path = staticmethod( EnvironmentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EnvironmentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) parse_common_organization_path = staticmethod( EnvironmentsClient.parse_common_organization_path ) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) parse_common_project_path = staticmethod( EnvironmentsClient.parse_common_project_path ) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) parse_common_location_path = staticmethod( EnvironmentsClient.parse_common_location_path @@ -76,7 +72,8 @@ class EnvironmentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EnvironmentsTransport: The transport used by the client instance. @@ -122,12 +119,12 @@ def transport(self) -> EnvironmentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -193,7 +189,6 @@ async def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -223,7 +218,6 @@ async def list_environments( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -253,6 +247,324 @@ async def list_environments( # Done; return the response. return response + async def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2beta1/services/environments/client.py b/google/cloud/dialogflow_v2beta1/services/environments/client.py index a9e38d254..c6e2de8d4 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/client.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -34,7 +32,8 @@ from google.cloud.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.types import environment - +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EnvironmentsGrpcTransport from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport @@ -53,7 +52,7 @@ class EnvironmentsClientMeta(type): _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EnvironmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -78,7 +77,8 @@ class EnvironmentsClient(metaclass=EnvironmentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -112,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -129,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -148,31 +149,43 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EnvironmentsTransport: The transport used by the client instance. + EnvironmentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def environment_path(project: str, environment: str,) -> str: - """Return a fully-qualified environment string.""" + """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]: - """Parse a environment path into its component segments.""" + """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 common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -185,7 +198,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -196,7 +209,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -207,7 +220,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -218,7 +231,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -232,12 +245,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EnvironmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -292,9 +305,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -306,12 +320,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -326,8 +342,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -368,7 +384,6 @@ def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -400,10 +415,8 @@ def list_environments( # there are no flattened fields. if not isinstance(request, environment.ListEnvironmentsRequest): request = environment.ListEnvironmentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -429,6 +442,329 @@ def list_environments( # Done; return the response. return response + def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2beta1/services/environments/pagers.py b/google/cloud/dialogflow_v2beta1/services/environments/pagers.py index c46469235..4307c677d 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -155,3 +153,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """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) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py index aff44bcdd..c72efee48 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py index d48fa645e..16fe7c632 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -46,21 +57,24 @@ class EnvironmentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -69,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -83,45 +97,156 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.list_environments: gapic_v1.method.wrap_method( self.list_environments, default_timeout=None, client_info=client_info, ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, default_timeout=None, client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, default_timeout=None, client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, default_timeout=None, client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, default_timeout=None, client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), } @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def delete_environment( + self, + ) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, Awaitable[environment.EnvironmentHistory] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py index 6fb0cd7e2..f2bfbb0a0 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -65,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -175,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -206,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -251,5 +252,149 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[[environment.GetEnvironmentRequest], environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[[environment.CreateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[[environment.UpdateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], environment.EnvironmentHistory + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py index 52b0b3ba7..af0d1bcc8 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -54,7 +52,7 @@ class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -81,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -95,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -109,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -167,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -256,5 +256,156 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory], + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py similarity index 92% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py index 95fd359ef..6bade52dd 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py @@ -17,6 +17,6 @@ from .async_client import FulfillmentsAsyncClient __all__ = ( - 'FulfillmentsClient', - 'FulfillmentsAsyncClient', + "FulfillmentsClient", + "FulfillmentsAsyncClient", ) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py similarity index 81% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py index fedbe1cc9..5f2a149b4 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py @@ -19,12 +19,12 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.types import fulfillment from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment @@ -46,16 +46,26 @@ class FulfillmentsAsyncClient: 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_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) + 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) + 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) + parse_common_location_path = staticmethod( + FulfillmentsClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -99,14 +109,18 @@ def transport(self) -> FulfillmentsTransport: """ return self._client.transport - get_transport_class = functools.partial(type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient)) + get_transport_class = functools.partial( + type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the fulfillments client. Args: @@ -144,17 +158,17 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def get_fulfillment(self, - request: fulfillment.GetFulfillmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: + async def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: r"""Retrieves the fulfillment. Args: @@ -198,8 +212,10 @@ async def get_fulfillment(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = fulfillment.GetFulfillmentRequest(request) @@ -219,31 +235,25 @@ async def get_fulfillment(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def update_fulfillment(self, - request: gcd_fulfillment.UpdateFulfillmentRequest = None, - *, - fulfillment: gcd_fulfillment.Fulfillment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: + async def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: r"""Updates the fulfillment. Args: @@ -290,8 +300,10 @@ async def update_fulfillment(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_fulfillment.UpdateFulfillmentRequest(request) @@ -313,26 +325,18 @@ async def update_fulfillment(self, # 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), - )), + 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, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -343,6 +347,4 @@ async def update_fulfillment(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FulfillmentsAsyncClient", -) +__all__ = ("FulfillmentsAsyncClient",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py similarity index 83% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/client.py index 759f1f7a0..ce04aee01 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py @@ -21,14 +21,14 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.types import fulfillment from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment @@ -45,13 +45,12 @@ class FulfillmentsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] _transport_registry["grpc"] = FulfillmentsGrpcTransport _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[FulfillmentsTransport]: + def get_transport_class(cls, label: str = None,) -> Type[FulfillmentsTransport]: """Returns an appropriate transport class. Args: @@ -141,8 +140,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: FulfillmentsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -161,75 +159,81 @@ def transport(self) -> FulfillmentsTransport: @staticmethod def fulfillment_path(project: str,) -> str: """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) + return "projects/{project}/agent/fulfillment".format(project=project,) @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format(folder=folder,) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format(organization=organization,) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format(project=project,) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FulfillmentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the fulfillments client. Args: @@ -273,7 +277,9 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) client_cert_source_func = None is_mtls = False @@ -314,8 +320,10 @@ def __init__(self, *, if isinstance(transport, FulfillmentsTransport): # transport is a FulfillmentsTransport instance. if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -334,14 +342,15 @@ def __init__(self, *, client_info=client_info, ) - def get_fulfillment(self, - request: fulfillment.GetFulfillmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: + def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: r"""Retrieves the fulfillment. Args: @@ -385,8 +394,10 @@ def get_fulfillment(self, # 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.') + 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. @@ -406,31 +417,25 @@ def get_fulfillment(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def update_fulfillment(self, - request: gcd_fulfillment.UpdateFulfillmentRequest = None, - *, - fulfillment: gcd_fulfillment.Fulfillment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: + def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: r"""Updates the fulfillment. Args: @@ -477,8 +482,10 @@ def update_fulfillment(self, # 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.') + 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. @@ -500,26 +507,18 @@ def update_fulfillment(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("fulfillment.name", request.fulfillment.name),) + ), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -530,6 +529,4 @@ def update_fulfillment(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "FulfillmentsClient", -) +__all__ = ("FulfillmentsClient",) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py similarity index 81% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py index 4b41f9212..d822b662b 100644 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py @@ -23,11 +23,11 @@ # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] -_transport_registry['grpc'] = FulfillmentsGrpcTransport -_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport +_transport_registry["grpc"] = FulfillmentsGrpcTransport +_transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport __all__ = ( - 'FulfillmentsTransport', - 'FulfillmentsGrpcTransport', - 'FulfillmentsGrpcAsyncIOTransport', + "FulfillmentsTransport", + "FulfillmentsGrpcTransport", + "FulfillmentsGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py similarity index 73% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py index 309c456bb..6df113cd3 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py @@ -21,7 +21,7 @@ import google.auth # type: ignore import google.api_core # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -31,7 +31,7 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', + "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: @@ -53,21 +53,23 @@ class FulfillmentsTransport(abc.ABC): """Abstract transport class for Fulfillments.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ) - DEFAULT_HOST: str = 'dialogflow.googleapis.com' + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -91,8 +93,8 @@ def __init__( your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) @@ -103,17 +105,19 @@ def __init__( # 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") + 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 - ) + 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) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials @@ -125,7 +129,9 @@ def __init__( # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" scopes_kwargs = {} @@ -142,7 +148,9 @@ def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[ # TODO: Remove this function once google-api-core >= 1.26.0 is required @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} @@ -163,36 +171,30 @@ 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.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, + self.update_fulfillment, default_timeout=None, client_info=client_info, ), - } + } @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - Union[ - fulfillment.Fulfillment, - Awaitable[fulfillment.Fulfillment] - ]]: + 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] - ]]: + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[gcd_fulfillment.Fulfillment, Awaitable[gcd_fulfillment.Fulfillment]], + ]: raise NotImplementedError() -__all__ = ( - 'FulfillmentsTransport', -) +__all__ = ("FulfillmentsTransport",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py similarity index 83% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py index cc48537f5..d2b8cc1b9 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py @@ -16,9 +16,9 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -42,21 +42,24 @@ class FulfillmentsGrpcTransport(FulfillmentsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -168,13 +171,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -209,7 +214,7 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) @property @@ -219,9 +224,9 @@ def grpc_channel(self) -> grpc.Channel: return self._grpc_channel @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - fulfillment.Fulfillment]: + def get_fulfillment( + self, + ) -> Callable[[fulfillment.GetFulfillmentRequest], fulfillment.Fulfillment]: r"""Return a callable for the get fulfillment method over gRPC. Retrieves the fulfillment. @@ -236,18 +241,20 @@ def get_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["get_fulfillment"] @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - gcd_fulfillment.Fulfillment]: + 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. @@ -262,15 +269,13 @@ def update_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["update_fulfillment"] -__all__ = ( - 'FulfillmentsGrpcTransport', -) +__all__ = ("FulfillmentsGrpcTransport",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py rename to google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py index 48d5527df..fb9f19f76 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py @@ -16,13 +16,13 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version -import grpc # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import fulfillment @@ -49,13 +49,15 @@ class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -86,22 +88,24 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -223,9 +227,11 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - Awaitable[fulfillment.Fulfillment]]: + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], Awaitable[fulfillment.Fulfillment] + ]: r"""Return a callable for the get fulfillment method over gRPC. Retrieves the fulfillment. @@ -240,18 +246,21 @@ def get_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["get_fulfillment"] @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - Awaitable[gcd_fulfillment.Fulfillment]]: + 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. @@ -266,15 +275,13 @@ def update_fulfillment(self) -> Callable[ # 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', + 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'] + return self._stubs["update_fulfillment"] -__all__ = ( - 'FulfillmentsGrpcAsyncIOTransport', -) +__all__ = ("FulfillmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/intents/__init__.py b/google/cloud/dialogflow_v2beta1/services/intents/__init__.py index 8719a9b64..5a2c263cf 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import IntentsClient from .async_client import IntentsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/intents/async_client.py b/google/cloud/dialogflow_v2beta1/services/intents/async_client.py index 023b4d49d..c071ce136 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,10 +32,9 @@ from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -57,31 +54,27 @@ class IntentsAsyncClient: parse_context_path = staticmethod(IntentsClient.parse_context_path) intent_path = staticmethod(IntentsClient.intent_path) parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod( IntentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( IntentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(IntentsClient.common_folder_path) parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) parse_common_organization_path = staticmethod( IntentsClient.parse_common_organization_path ) - common_project_path = staticmethod(IntentsClient.common_project_path) parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: IntentsTransport: The transport used by the client instance. @@ -127,12 +120,12 @@ def transport(self) -> IntentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, IntentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -206,7 +198,6 @@ async def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +227,6 @@ async def list_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -303,7 +293,6 @@ async def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -339,7 +328,6 @@ async def get_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -407,7 +395,6 @@ async def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -443,7 +430,6 @@ async def create_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -476,7 +462,7 @@ async def update_intent( request: gcd_intent.UpdateIntentRequest = None, *, intent: gcd_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -510,7 +496,6 @@ async def update_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -546,7 +531,6 @@ async def update_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -605,7 +589,6 @@ async def delete_intent( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -626,7 +609,6 @@ async def delete_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -697,7 +679,6 @@ async def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -728,7 +709,6 @@ async def batch_update_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -758,7 +738,7 @@ async def batch_update_intents( response, self._client._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -800,7 +780,6 @@ async def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -840,10 +819,8 @@ async def batch_delete_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if intents: request.intents.extend(intents) @@ -868,8 +845,8 @@ async def batch_delete_intents( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2beta1/services/intents/client.py b/google/cloud/dialogflow_v2beta1/services/intents/client.py index 392e2d270..eaddb5108 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/client.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,10 +36,9 @@ from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class IntentsClientMeta(type): _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IntentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +82,8 @@ class IntentsClient(metaclass=IntentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -119,7 +117,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +135,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,23 +154,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - IntentsTransport: The transport used by the client instance. + IntentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -180,20 +180,20 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -206,7 +206,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -239,7 +239,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -253,12 +253,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IntentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -313,9 +313,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -327,12 +328,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -347,8 +350,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -397,7 +400,6 @@ def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -429,10 +431,8 @@ def list_intents( # there are no flattened fields. if not isinstance(request, intent.ListIntentsRequest): request = intent.ListIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: @@ -495,7 +495,6 @@ def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -533,10 +532,8 @@ def get_intent( # there are no flattened fields. if not isinstance(request, intent.GetIntentRequest): request = intent.GetIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if language_code is not None: @@ -600,7 +597,6 @@ def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -638,10 +634,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.CreateIntentRequest): request = gcd_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -670,7 +664,7 @@ def update_intent( request: gcd_intent.UpdateIntentRequest = None, *, intent: gcd_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -704,7 +698,6 @@ def update_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -742,10 +735,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.UpdateIntentRequest): request = gcd_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -800,7 +791,6 @@ def delete_intent( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -823,10 +813,8 @@ def delete_intent( # there are no flattened fields. if not isinstance(request, intent.DeleteIntentRequest): request = intent.DeleteIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -893,7 +881,6 @@ def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -926,10 +913,8 @@ def batch_update_intents( # there are no flattened fields. if not isinstance(request, intent.BatchUpdateIntentsRequest): request = intent.BatchUpdateIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -955,7 +940,7 @@ def batch_update_intents( response, self._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -997,7 +982,6 @@ def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1039,10 +1023,8 @@ def batch_delete_intents( # there are no flattened fields. if not isinstance(request, intent.BatchDeleteIntentsRequest): request = intent.BatchDeleteIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intents is not None: @@ -1065,8 +1047,8 @@ def batch_delete_intents( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflow_v2beta1/services/intents/pagers.py b/google/cloud/dialogflow_v2beta1/services/intents/pagers.py index 7a8547bd6..9199c11b1 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py index 41fde33b5..974a58103 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py index b49fd88d1..ff39e5c0d 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -50,21 +60,24 @@ class IntentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -148,65 +208,61 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.ListIntentsRequest], - typing.Union[ - intent.ListIntentsResponse, typing.Awaitable[intent.ListIntentsResponse] - ], + Union[intent.ListIntentsResponse, Awaitable[intent.ListIntentsResponse]], ]: raise NotImplementedError() @property def get_intent( self, - ) -> typing.Callable[ - [intent.GetIntentRequest], - typing.Union[intent.Intent, typing.Awaitable[intent.Intent]], + ) -> Callable[ + [intent.GetIntentRequest], Union[intent.Intent, Awaitable[intent.Intent]] ]: raise NotImplementedError() @property def create_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.CreateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.UpdateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def delete_intent( self, - ) -> typing.Callable[ - [intent.DeleteIntentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [intent.DeleteIntentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def batch_update_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchUpdateIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchDeleteIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py index 792e437cc..a1b2ec128 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -345,7 +345,7 @@ def update_intent( return self._stubs["update_intent"] @property - def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: + def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty_pb2.Empty]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent and its direct or @@ -365,14 +365,14 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchUpdateIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -394,14 +394,14 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchDeleteIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -423,7 +423,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py index f8cfe4546..101c3b56a 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -58,7 +55,7 @@ class IntentsGrpcAsyncIOTransport(IntentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -355,7 +354,7 @@ def update_intent( @property def delete_intent( self, - ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent and its direct or @@ -375,14 +374,16 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchUpdateIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -404,14 +405,16 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchDeleteIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -433,7 +436,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py index be24a37d1..24204c982 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import KnowledgeBasesClient from .async_client import KnowledgeBasesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py index dfefff910..b621ba17a 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport from .client import KnowledgeBasesClient @@ -52,31 +49,26 @@ class KnowledgeBasesAsyncClient: parse_knowledge_base_path = staticmethod( KnowledgeBasesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( KnowledgeBasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( KnowledgeBasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) parse_common_folder_path = staticmethod( KnowledgeBasesClient.parse_common_folder_path ) - common_organization_path = staticmethod( KnowledgeBasesClient.common_organization_path ) parse_common_organization_path = staticmethod( KnowledgeBasesClient.parse_common_organization_path ) - common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) parse_common_project_path = staticmethod( KnowledgeBasesClient.parse_common_project_path ) - common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) parse_common_location_path = staticmethod( KnowledgeBasesClient.parse_common_location_path @@ -84,7 +76,8 @@ class KnowledgeBasesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> KnowledgeBasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: KnowledgeBasesTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> KnowledgeBasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the knowledge bases client. + """Instantiates the knowledge bases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = KnowledgeBasesClient( credentials=credentials, transport=transport, @@ -201,7 +193,6 @@ async def list_knowledge_bases( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -231,7 +222,6 @@ async def list_knowledge_bases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -287,7 +277,6 @@ async def get_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -324,7 +313,6 @@ async def get_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -382,7 +370,6 @@ async def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -419,7 +406,6 @@ async def create_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -471,7 +457,6 @@ async def delete_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -492,7 +477,6 @@ async def delete_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -520,7 +504,7 @@ async def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -549,7 +533,6 @@ async def update_knowledge_base( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -586,7 +569,6 @@ async def update_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py index 366e4f7ad..dc4f40079 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KnowledgeBasesGrpcTransport from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class KnowledgeBasesClientMeta(type): _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[KnowledgeBasesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,23 +151,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> KnowledgeBasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - KnowledgeBasesTransport: The transport used by the client instance. + KnowledgeBasesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def knowledge_base_path(project: str, knowledge_base: str,) -> str: - """Return a fully-qualified knowledge_base string.""" + """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]: - """Parse a knowledge_base path into its component segments.""" + """Parses a knowledge_base path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path ) @@ -176,7 +176,7 @@ def parse_knowledge_base_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -189,7 +189,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -200,7 +200,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -211,7 +211,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -222,7 +222,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -236,12 +236,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, KnowledgeBasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the knowledge bases client. + """Instantiates the knowledge bases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -296,9 +296,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -310,12 +311,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -330,8 +333,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -372,7 +375,6 @@ def list_knowledge_bases( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -404,10 +406,8 @@ def list_knowledge_bases( # there are no flattened fields. if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): request = knowledge_base.ListKnowledgeBasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -459,7 +459,6 @@ def get_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -498,10 +497,8 @@ def get_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): request = knowledge_base.GetKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -555,7 +552,6 @@ def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -594,10 +590,8 @@ def create_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -645,7 +639,6 @@ def delete_knowledge_base( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -668,10 +661,8 @@ def delete_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): request = knowledge_base.DeleteKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -695,7 +686,7 @@ def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -724,7 +715,6 @@ def update_knowledge_base( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -763,10 +753,8 @@ def update_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py index 32d735175..63661986c 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py index a3ac400b0..38da4326d 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py index 900d39a5f..23af5591d 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class KnowledgeBasesTransport(abc.ABC): """Abstract transport class for KnowledgeBases.""" @@ -48,21 +58,24 @@ class KnowledgeBasesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -139,11 +199,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_knowledge_bases( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.ListKnowledgeBasesRequest], - typing.Union[ + Union[ knowledge_base.ListKnowledgeBasesResponse, - typing.Awaitable[knowledge_base.ListKnowledgeBasesResponse], + Awaitable[knowledge_base.ListKnowledgeBasesResponse], ], ]: raise NotImplementedError() @@ -151,22 +211,20 @@ def list_knowledge_bases( @property def get_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.GetKnowledgeBaseRequest], - typing.Union[ - knowledge_base.KnowledgeBase, typing.Awaitable[knowledge_base.KnowledgeBase] - ], + Union[knowledge_base.KnowledgeBase, Awaitable[knowledge_base.KnowledgeBase]], ]: raise NotImplementedError() @property def create_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.CreateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() @@ -174,20 +232,20 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.DeleteKnowledgeBaseRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def update_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py index 563d0d737..72979a176 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -322,7 +322,7 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty.Empty]: + ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty_pb2.Empty]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -344,7 +344,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py index 589b6cf50..3194691bb 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .grpc import KnowledgeBasesGrpcTransport @@ -56,7 +53,7 @@ class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -327,7 +326,9 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -349,7 +350,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2beta1/services/participants/__init__.py b/google/cloud/dialogflow_v2beta1/services/participants/__init__.py index 9ebfb1f70..942327781 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ParticipantsClient from .async_client import ParticipantsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py index ac4e64e35..469478d53 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.participants import pagers from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant from google.cloud.dialogflow_v2beta1.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport from .client import ParticipantsClient @@ -63,27 +60,22 @@ class ParticipantsAsyncClient: parse_session_entity_type_path = staticmethod( ParticipantsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( ParticipantsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ParticipantsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ParticipantsClient.common_folder_path) parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) - common_organization_path = staticmethod(ParticipantsClient.common_organization_path) parse_common_organization_path = staticmethod( ParticipantsClient.parse_common_organization_path ) - common_project_path = staticmethod(ParticipantsClient.common_project_path) parse_common_project_path = staticmethod( ParticipantsClient.parse_common_project_path ) - common_location_path = staticmethod(ParticipantsClient.common_location_path) parse_common_location_path = staticmethod( ParticipantsClient.parse_common_location_path @@ -91,7 +83,8 @@ class ParticipantsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -106,7 +99,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -123,7 +116,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ParticipantsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ParticipantsTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> ParticipantsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ParticipantsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the participants client. + """Instantiates the participants client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ParticipantsClient( credentials=credentials, transport=transport, @@ -211,7 +203,6 @@ async def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -238,7 +229,6 @@ async def create_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -286,7 +276,6 @@ async def get_participant( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -313,7 +302,6 @@ async def get_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -361,7 +349,6 @@ async def list_participants( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -391,7 +378,6 @@ async def list_participants( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -426,7 +412,7 @@ async def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -449,7 +435,6 @@ async def update_participant( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -476,7 +461,6 @@ async def update_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -519,8 +503,8 @@ async def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (:class:`google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest`): @@ -546,7 +530,6 @@ async def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -573,7 +556,6 @@ async def analyze_content( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -589,7 +571,9 @@ async def analyze_content( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -641,7 +625,6 @@ async def suggest_articles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -668,7 +651,6 @@ async def suggest_articles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -716,7 +698,6 @@ async def suggest_faq_answers( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -743,7 +724,6 @@ async def suggest_faq_answers( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -791,7 +771,6 @@ async def suggest_smart_replies( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -818,7 +797,6 @@ async def suggest_smart_replies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -861,7 +839,7 @@ async def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in @@ -875,7 +853,6 @@ async def list_suggestions( request (:class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest`): The request object. The request message for [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -892,7 +869,6 @@ async def list_suggestions( """ # Create or coerce a protobuf request object. - request = participant.ListSuggestionsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -949,7 +925,6 @@ async def compile_suggestion( request (:class:`google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest`): The request object. The request message for [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -963,7 +938,6 @@ async def compile_suggestion( """ # Create or coerce a protobuf request object. - request = participant.CompileSuggestionRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2beta1/services/participants/client.py b/google/cloud/dialogflow_v2beta1/services/participants/client.py index ae9ace66c..7b5583207 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,8 +34,7 @@ from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant from google.cloud.dialogflow_v2beta1.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ParticipantsGrpcTransport from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class ParticipantsClientMeta(type): _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ParticipantsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ParticipantsClient(metaclass=ParticipantsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ParticipantsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ParticipantsTransport: The transport used by the client instance. + ParticipantsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -176,14 +176,14 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -192,27 +192,27 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified message string.""" + """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]: - """Parse a message path into its component segments.""" + """Parses a message path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path, @@ -221,14 +221,14 @@ def parse_message_path(path: str) -> Dict[str, str]: @staticmethod def participant_path(project: str, conversation: str, participant: str,) -> str: - """Return a fully-qualified participant string.""" + """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]: - """Parse a participant path into its component segments.""" + """Parses a participant path into its component segments.""" m = re.match( r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path, @@ -237,14 +237,14 @@ def parse_participant_path(path: str) -> Dict[str, str]: @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -253,7 +253,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -266,7 +266,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -277,7 +277,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -288,7 +288,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -299,7 +299,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -313,12 +313,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ParticipantsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the participants client. + """Instantiates the participants client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -373,9 +373,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -387,12 +388,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -407,8 +410,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -452,7 +455,6 @@ def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -481,10 +483,8 @@ def create_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.CreateParticipantRequest): request = gcd_participant.CreateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -528,7 +528,6 @@ def get_participant( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -557,10 +556,8 @@ def get_participant( # there are no flattened fields. if not isinstance(request, participant.GetParticipantRequest): request = participant.GetParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -604,7 +601,6 @@ def list_participants( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -636,10 +632,8 @@ def list_participants( # there are no flattened fields. if not isinstance(request, participant.ListParticipantsRequest): request = participant.ListParticipantsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -670,7 +664,7 @@ def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -693,7 +687,6 @@ def update_participant( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -722,10 +715,8 @@ def update_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.UpdateParticipantRequest): request = gcd_participant.UpdateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -764,8 +755,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest): @@ -791,7 +782,6 @@ def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -820,10 +810,8 @@ def analyze_content( # there are no flattened fields. if not isinstance(request, gcd_participant.AnalyzeContentRequest): request = gcd_participant.AnalyzeContentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -880,7 +868,6 @@ def suggest_articles( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -909,10 +896,8 @@ def suggest_articles( # there are no flattened fields. if not isinstance(request, participant.SuggestArticlesRequest): request = participant.SuggestArticlesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -956,7 +941,6 @@ def suggest_faq_answers( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -985,10 +969,8 @@ def suggest_faq_answers( # there are no flattened fields. if not isinstance(request, participant.SuggestFaqAnswersRequest): request = participant.SuggestFaqAnswersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1032,7 +1014,6 @@ def suggest_smart_replies( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1061,10 +1042,8 @@ def suggest_smart_replies( # there are no flattened fields. if not isinstance(request, participant.SuggestSmartRepliesRequest): request = participant.SuggestSmartRepliesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1103,7 +1082,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in @@ -1117,7 +1096,6 @@ def list_suggestions( request (google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest): The request object. The request message for [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1134,7 +1112,6 @@ def list_suggestions( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a participant.ListSuggestionsRequest. # There's no risk of modifying the input as we've already verified @@ -1192,7 +1169,6 @@ def compile_suggestion( request (google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest): The request object. The request message for [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1206,7 +1182,6 @@ def compile_suggestion( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a participant.CompileSuggestionRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2beta1/services/participants/pagers.py b/google/cloud/dialogflow_v2beta1/services/participants/pagers.py index e2b2278e8..d830b5dc1 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py index 91a4cec1c..522813c1c 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py index 6c63884a8..10e1fa8b9 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ParticipantsTransport(abc.ABC): """Abstract transport class for Participants.""" @@ -47,21 +57,24 @@ class ParticipantsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -128,7 +188,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -156,33 +218,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.CreateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def get_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.GetParticipantRequest], - typing.Union[ - participant.Participant, typing.Awaitable[participant.Participant] - ], + Union[participant.Participant, Awaitable[participant.Participant]], ]: raise NotImplementedError() @property def list_participants( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListParticipantsRequest], - typing.Union[ + Union[ participant.ListParticipantsResponse, - typing.Awaitable[participant.ListParticipantsResponse], + Awaitable[participant.ListParticipantsResponse], ], ]: raise NotImplementedError() @@ -190,22 +248,20 @@ def list_participants( @property def update_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.UpdateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def analyze_content( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.AnalyzeContentRequest], - typing.Union[ + Union[ gcd_participant.AnalyzeContentResponse, - typing.Awaitable[gcd_participant.AnalyzeContentResponse], + Awaitable[gcd_participant.AnalyzeContentResponse], ], ]: raise NotImplementedError() @@ -213,11 +269,11 @@ def analyze_content( @property def suggest_articles( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestArticlesRequest], - typing.Union[ + Union[ participant.SuggestArticlesResponse, - typing.Awaitable[participant.SuggestArticlesResponse], + Awaitable[participant.SuggestArticlesResponse], ], ]: raise NotImplementedError() @@ -225,11 +281,11 @@ def suggest_articles( @property def suggest_faq_answers( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestFaqAnswersRequest], - typing.Union[ + Union[ participant.SuggestFaqAnswersResponse, - typing.Awaitable[participant.SuggestFaqAnswersResponse], + Awaitable[participant.SuggestFaqAnswersResponse], ], ]: raise NotImplementedError() @@ -237,11 +293,11 @@ def suggest_faq_answers( @property def suggest_smart_replies( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestSmartRepliesRequest], - typing.Union[ + Union[ participant.SuggestSmartRepliesResponse, - typing.Awaitable[participant.SuggestSmartRepliesResponse], + Awaitable[participant.SuggestSmartRepliesResponse], ], ]: raise NotImplementedError() @@ -249,11 +305,11 @@ def suggest_smart_replies( @property def list_suggestions( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListSuggestionsRequest], - typing.Union[ + Union[ participant.ListSuggestionsResponse, - typing.Awaitable[participant.ListSuggestionsResponse], + Awaitable[participant.ListSuggestionsResponse], ], ]: raise NotImplementedError() @@ -261,11 +317,11 @@ def list_suggestions( @property def compile_suggestion( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.CompileSuggestionRequest], - typing.Union[ + Union[ participant.CompileSuggestionResponse, - typing.Awaitable[participant.CompileSuggestionResponse], + Awaitable[participant.CompileSuggestionResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py index 04560ca1e..4822f6de4 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -346,8 +346,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -481,7 +481,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py index ad713f7d5..8e9b88110 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .grpc import ParticipantsGrpcTransport @@ -55,7 +52,7 @@ class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -356,8 +355,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -494,7 +493,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py index c0dca267f..cbd406b49 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionEntityTypesClient from .async_client import SessionEntityTypesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py index 1fac133d4..da8d49e7f 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport from .client import SessionEntityTypesClient @@ -57,31 +54,26 @@ class SessionEntityTypesAsyncClient: parse_session_entity_type_path = staticmethod( SessionEntityTypesClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionEntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionEntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod( SessionEntityTypesClient.parse_common_folder_path ) - common_organization_path = staticmethod( SessionEntityTypesClient.common_organization_path ) parse_common_organization_path = staticmethod( SessionEntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) parse_common_project_path = staticmethod( SessionEntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) parse_common_location_path = staticmethod( SessionEntityTypesClient.parse_common_location_path @@ -89,7 +81,8 @@ class SessionEntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionEntityTypesTransport: The transport used by the client instance. @@ -136,12 +129,12 @@ def transport(self) -> SessionEntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -173,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -217,7 +209,6 @@ async def list_session_entity_types( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -247,7 +238,6 @@ async def list_session_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -312,7 +302,6 @@ async def get_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -347,7 +336,6 @@ async def get_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -417,7 +405,6 @@ async def create_session_entity_type( This corresponds to the ``session_entity_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -452,7 +439,6 @@ async def create_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -483,7 +469,7 @@ async def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -511,7 +497,6 @@ async def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -546,7 +531,6 @@ async def update_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -609,7 +593,6 @@ async def delete_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -630,7 +613,6 @@ async def delete_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py index 37ff5e1b2..b59ef0cba 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,8 +36,7 @@ from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionEntityTypesGrpcTransport from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class SessionEntityTypesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SessionEntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,23 +156,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionEntityTypesTransport: The transport used by the client instance. + SessionEntityTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -182,7 +182,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -195,7 +195,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -206,7 +206,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -242,12 +242,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionEntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -302,9 +302,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -316,12 +317,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -336,8 +339,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -388,7 +391,6 @@ def list_session_entity_types( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -420,10 +422,8 @@ def list_session_entity_types( # there are no flattened fields. if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): request = session_entity_type.ListSessionEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -486,7 +486,6 @@ def get_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -523,10 +522,8 @@ def get_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): request = session_entity_type.GetSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -592,7 +589,6 @@ def create_session_entity_type( This corresponds to the ``session_entity_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -631,10 +627,8 @@ def create_session_entity_type( request, gcd_session_entity_type.CreateSessionEntityTypeRequest ): request = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -663,7 +657,7 @@ def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -691,7 +685,6 @@ def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -730,10 +723,8 @@ def update_session_entity_type( request, gcd_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -794,7 +785,6 @@ def delete_session_entity_type( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -817,10 +807,8 @@ def delete_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): request = session_entity_type.DeleteSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py index f92cbf966..5f010f5ef 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py index 606f91160..633fd32cb 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py index e3e62fc17..ad4cbed37 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import session_entity_type from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -50,21 +60,24 @@ class SessionEntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -73,7 +86,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_session_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.ListSessionEntityTypesRequest], - typing.Union[ + Union[ session_entity_type.ListSessionEntityTypesResponse, - typing.Awaitable[session_entity_type.ListSessionEntityTypesResponse], + Awaitable[session_entity_type.ListSessionEntityTypesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_session_entity_types( @property def get_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.GetSessionEntityTypeRequest], - typing.Union[ + Union[ session_entity_type.SessionEntityType, - typing.Awaitable[session_entity_type.SessionEntityType], + Awaitable[session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_session_entity_type( @property def create_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_session_entity_type( @property def update_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.DeleteSessionEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py index 6ef126d94..93f87cf86 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -30,8 +28,7 @@ from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -361,7 +361,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> Callable[[session_entity_type.DeleteSessionEntityTypeRequest], empty.Empty]: + ) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete session entity type method over gRPC. Deletes the specified session entity type. @@ -383,7 +385,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py index 10e5ecdfd..57b303dc5 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,8 +29,7 @@ from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import SessionEntityTypesGrpcTransport @@ -58,7 +55,7 @@ class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -366,7 +365,7 @@ def update_session_entity_type( def delete_session_entity_type( self, ) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty.Empty] + [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete session entity type method over gRPC. @@ -389,7 +388,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py b/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py index 3b2a59a9d..0adeafb97 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionsClient from .async_client import SessionsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py index c62121f7d..7ee96e0f1 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,17 +29,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -71,31 +68,27 @@ class SessionsAsyncClient: parse_session_entity_type_path = staticmethod( SessionsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionsClient.common_folder_path) parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) parse_common_organization_path = staticmethod( SessionsClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionsClient.common_project_path) parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -110,7 +103,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -127,7 +120,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionsTransport: The transport used by the client instance. @@ -141,12 +134,12 @@ def transport(self) -> SessionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -178,7 +171,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -253,7 +245,6 @@ async def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -280,7 +271,6 @@ async def detect_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: @@ -294,7 +284,9 @@ async def detect_intent( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/client.py b/google/cloud/dialogflow_v2beta1/services/sessions/client.py index 9800ee01b..0a5e34b6d 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/client.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -45,8 +43,7 @@ from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -65,7 +62,7 @@ class SessionsClientMeta(type): _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SessionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -92,7 +89,8 @@ class SessionsClient(metaclass=SessionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -126,7 +124,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -143,7 +142,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -162,23 +161,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionsTransport: The transport used by the client instance. + SessionsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def context_path(project: str, session: str, context: str,) -> str: - """Return a fully-qualified context string.""" + """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]: - """Parse a context path into its component segments.""" + """Parses a context path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path, @@ -187,14 +187,14 @@ def parse_context_path(path: str) -> Dict[str, str]: @staticmethod def document_path(project: str, knowledge_base: str, document: str,) -> str: - """Return a fully-qualified document string.""" + """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]: - """Parse a document path into its component segments.""" + """Parses a document path into its component segments.""" m = re.match( r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path, @@ -203,27 +203,27 @@ def parse_document_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """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]: - """Parse a intent path into its component segments.""" + """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: - """Return a fully-qualified session string.""" + """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]: - """Parse a session path into its component segments.""" + """Parses a session path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path ) @@ -231,14 +231,14 @@ def parse_session_path(path: str) -> Dict[str, str]: @staticmethod def session_entity_type_path(project: str, session: str, entity_type: str,) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/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]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -247,7 +247,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -260,7 +260,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -271,7 +271,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -282,7 +282,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -293,7 +293,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -307,12 +307,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -367,9 +367,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -381,12 +382,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -401,8 +404,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -484,7 +487,6 @@ def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -513,10 +515,8 @@ def detect_intent( # there are no flattened fields. if not isinstance(request, gcd_session.DetectIntentRequest): request = gcd_session.DetectIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py index 0ca6c76ea..db0f7d045 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py index 24431128f..a2804b91d 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -47,21 +57,24 @@ class SessionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -70,7 +83,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=220.0, ), default_timeout=220.0, @@ -132,11 +194,11 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session.DetectIntentRequest], - typing.Union[ + Union[ gcd_session.DetectIntentResponse, - typing.Awaitable[gcd_session.DetectIntentResponse], + Awaitable[gcd_session.DetectIntentResponse], ], ]: raise NotImplementedError() @@ -144,11 +206,11 @@ def detect_intent( @property def streaming_detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.StreamingDetectIntentRequest], - typing.Union[ + Union[ session.StreamingDetectIntentResponse, - typing.Awaitable[session.StreamingDetectIntentResponse], + Awaitable[session.StreamingDetectIntentResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py index c1fc1907c..aa5a28ca9 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py index ad283b9d5..7389490de 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -57,7 +54,7 @@ class SessionsGrpcAsyncIOTransport(SessionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py b/google/cloud/dialogflow_v2beta1/services/versions/__init__.py similarity index 93% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py rename to google/cloud/dialogflow_v2beta1/services/versions/__init__.py index 630246bde..586be1818 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/__init__.py @@ -17,6 +17,6 @@ from .async_client import VersionsAsyncClient __all__ = ( - 'VersionsClient', - 'VersionsAsyncClient', + "VersionsClient", + "VersionsAsyncClient", ) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py b/google/cloud/dialogflow_v2beta1/services/versions/async_client.py similarity index 81% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py rename to google/cloud/dialogflow_v2beta1/services/versions/async_client.py index 4a52fb612..05f84d7fa 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/async_client.py @@ -19,12 +19,12 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.versions import pagers from google.cloud.dialogflow_v2beta1.types import version @@ -48,12 +48,18 @@ class VersionsAsyncClient: version_path = staticmethod(VersionsClient.version_path) parse_version_path = staticmethod(VersionsClient.parse_version_path) - common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_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) + 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) @@ -101,14 +107,18 @@ def transport(self) -> VersionsTransport: """ return self._client.transport - get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + get_transport_class = functools.partial( + type(VersionsClient).get_transport_class, type(VersionsClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VersionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the versions client. Args: @@ -146,17 +156,17 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def list_versions(self, - request: version.ListVersionsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsAsyncPager: + async def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: r"""Returns the list of all versions of the specified agent. @@ -194,8 +204,10 @@ async def list_versions(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.ListVersionsRequest(request) @@ -215,39 +227,30 @@ async def list_versions(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + 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, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - async def get_version(self, - request: version.GetVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: + async def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: r"""Retrieves the specified agent version. Args: @@ -299,8 +302,10 @@ async def get_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.GetVersionRequest(request) @@ -320,31 +325,25 @@ async def get_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def create_version(self, - request: gcd_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcd_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + async def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Creates an agent version. The new version points to the agent instance in the "default" environment. @@ -404,8 +403,10 @@ async def create_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_version.CreateVersionRequest(request) @@ -427,31 +428,25 @@ async def create_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def update_version(self, - request: gcd_version.UpdateVersionRequest = None, - *, - version: gcd_version.Version = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + async def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Updates the specified agent version. Note that this method does not allow you to update the state of the agent the given version points to. It @@ -514,8 +509,10 @@ async def update_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = gcd_version.UpdateVersionRequest(request) @@ -537,30 +534,26 @@ async def update_version(self, # 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), - )), + 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, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def delete_version(self, - request: version.DeleteVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: + async def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: r"""Delete the specified agent version. Args: @@ -588,8 +581,10 @@ async def delete_version(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = version.DeleteVersionRequest(request) @@ -609,23 +604,15 @@ async def delete_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, + request, retry=retry, timeout=timeout, metadata=metadata, ) - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -636,6 +623,4 @@ async def delete_version(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "VersionsAsyncClient", -) +__all__ = ("VersionsAsyncClient",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py b/google/cloud/dialogflow_v2beta1/services/versions/client.py similarity index 82% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py rename to google/cloud/dialogflow_v2beta1/services/versions/client.py index 21424201d..6694d7df5 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/client.py @@ -21,14 +21,14 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.dialogflow_v2beta1.services.versions import pagers from google.cloud.dialogflow_v2beta1.types import version @@ -47,13 +47,12 @@ class VersionsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] _transport_registry["grpc"] = VersionsGrpcTransport _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[VersionsTransport]: + def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: """Returns an appropriate transport class. Args: @@ -143,8 +142,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: VersionsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -161,77 +159,87 @@ def transport(self) -> VersionsTransport: return self._transport @staticmethod - def version_path(project: str,version: str,) -> str: + 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, ) + return "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: + 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) + 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: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format(folder=folder,) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format(organization=organization,) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format(project=project,) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VersionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the versions client. Args: @@ -275,7 +283,9 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) client_cert_source_func = None is_mtls = False @@ -316,8 +326,10 @@ def __init__(self, *, if isinstance(transport, VersionsTransport): # transport is a VersionsTransport instance. if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -336,14 +348,15 @@ def __init__(self, *, client_info=client_info, ) - def list_versions(self, - request: version.ListVersionsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsPager: + def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: r"""Returns the list of all versions of the specified agent. @@ -381,8 +394,10 @@ def list_versions(self, # 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.') + 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. @@ -402,39 +417,30 @@ def list_versions(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + 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, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - def get_version(self, - request: version.GetVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: + def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: r"""Retrieves the specified agent version. Args: @@ -486,8 +492,10 @@ def get_version(self, # 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.') + 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. @@ -507,31 +515,25 @@ def get_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def create_version(self, - request: gcd_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcd_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Creates an agent version. The new version points to the agent instance in the "default" environment. @@ -591,8 +593,10 @@ def create_version(self, # 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.') + 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. @@ -614,31 +618,25 @@ def create_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def update_version(self, - request: gcd_version.UpdateVersionRequest = None, - *, - version: gcd_version.Version = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_version.Version: + def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: r"""Updates the specified agent version. Note that this method does not allow you to update the state of the agent the given version points to. It @@ -701,8 +699,10 @@ def update_version(self, # 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.') + 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. @@ -724,30 +724,26 @@ def update_version(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("version.name", request.version.name),) + ), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def delete_version(self, - request: version.DeleteVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: + def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: r"""Delete the specified agent version. Args: @@ -775,8 +771,10 @@ def delete_version(self, # 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.') + 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. @@ -796,23 +794,15 @@ def delete_version(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, + request, retry=retry, timeout=timeout, metadata=metadata, ) - - - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -823,6 +813,4 @@ def delete_version(self, DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "VersionsClient", -) +__all__ = ("VersionsClient",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py b/google/cloud/dialogflow_v2beta1/services/versions/pagers.py similarity index 86% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py rename to google/cloud/dialogflow_v2beta1/services/versions/pagers.py index 436ffd3d9..fe16a182a 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/pagers.py @@ -13,7 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) from google.cloud.dialogflow_v2beta1.types import version @@ -35,12 +44,15 @@ class ListVersionsPager: 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]] = ()): + + def __init__( + self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -74,7 +86,7 @@ def __iter__(self) -> Iterable[version.Version]: yield from page.versions def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListVersionsAsyncPager: @@ -94,12 +106,15 @@ class ListVersionsAsyncPager: 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]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -137,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + 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/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py similarity index 81% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py rename to google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py index dfb70ce95..c5a42a0e8 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py @@ -23,11 +23,11 @@ # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] -_transport_registry['grpc'] = VersionsGrpcTransport -_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport +_transport_registry["grpc"] = VersionsGrpcTransport +_transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport __all__ = ( - 'VersionsTransport', - 'VersionsGrpcTransport', - 'VersionsGrpcAsyncIOTransport', + "VersionsTransport", + "VersionsGrpcTransport", + "VersionsGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py similarity index 67% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py rename to google/cloud/dialogflow_v2beta1/services/versions/transports/base.py index 53d755ba1..82d478c05 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py @@ -21,7 +21,7 @@ import google.auth # type: ignore import google.api_core # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -32,7 +32,7 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', + "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: @@ -54,21 +54,23 @@ class VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ) - DEFAULT_HOST: str = 'dialogflow.googleapis.com' + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -92,8 +94,8 @@ def __init__( your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) @@ -104,17 +106,19 @@ def __init__( # 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") + 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 - ) + 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) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials @@ -126,7 +130,9 @@ def __init__( # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" scopes_kwargs = {} @@ -143,7 +149,9 @@ def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[ # TODO: Remove this function once google-api-core >= 1.26.0 is required @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} @@ -164,78 +172,65 @@ 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.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.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.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.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, + self.delete_version, default_timeout=None, client_info=client_info, ), - } + } @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - Union[ - version.ListVersionsResponse, - Awaitable[version.ListVersionsResponse] - ]]: + 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] - ]]: + 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] - ]]: + 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] - ]]: + 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] - ]]: + def delete_version( + self, + ) -> Callable[ + [version.DeleteVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() -__all__ = ( - 'VersionsTransport', -) +__all__ = ("VersionsTransport",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py similarity index 80% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py rename to google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py index 8e93cf2c8..7d150e364 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py @@ -16,9 +16,9 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -43,21 +43,24 @@ class VersionsGrpcTransport(VersionsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -169,13 +172,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -210,7 +215,7 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) @property @@ -220,9 +225,9 @@ def grpc_channel(self) -> grpc.Channel: return self._grpc_channel @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: + 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 @@ -238,18 +243,16 @@ def list_versions(self) -> Callable[ # 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', + 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'] + return self._stubs["list_versions"] @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - version.Version]: + 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. @@ -264,18 +267,18 @@ def get_version(self) -> Callable[ # 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', + 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'] + return self._stubs["get_version"] @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - gcd_version.Version]: + 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. @@ -292,18 +295,18 @@ def create_version(self) -> Callable[ # 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', + 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'] + return self._stubs["create_version"] @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - gcd_version.Version]: + 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. @@ -322,18 +325,18 @@ def update_version(self) -> Callable[ # 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', + 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'] + return self._stubs["update_version"] @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - empty_pb2.Empty]: + 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. @@ -348,15 +351,13 @@ def delete_version(self) -> Callable[ # 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', + 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'] + return self._stubs["delete_version"] -__all__ = ( - 'VersionsGrpcTransport', -) +__all__ = ("VersionsGrpcTransport",) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py similarity index 80% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py rename to google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py index cf741b29a..0223a30ab 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py @@ -16,13 +16,13 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version -import grpc # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflow_v2beta1.types import version @@ -50,13 +50,15 @@ class VersionsGrpcAsyncIOTransport(VersionsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -87,22 +89,24 @@ def create_channel(cls, credentials_file=credentials_file, quota_project_id=quota_project_id, **self_signed_jwt_kwargs, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiate the transport. Args: @@ -224,9 +228,11 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - Awaitable[version.ListVersionsResponse]]: + 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 @@ -242,18 +248,18 @@ def list_versions(self) -> Callable[ # 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', + 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'] + return self._stubs["list_versions"] @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - Awaitable[version.Version]]: + 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. @@ -268,18 +274,18 @@ def get_version(self) -> Callable[ # 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', + 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'] + return self._stubs["get_version"] @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - Awaitable[gcd_version.Version]]: + 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. @@ -296,18 +302,18 @@ def create_version(self) -> Callable[ # 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', + 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'] + return self._stubs["create_version"] @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - Awaitable[gcd_version.Version]]: + 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. @@ -326,18 +332,18 @@ def update_version(self) -> Callable[ # 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', + 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'] + return self._stubs["update_version"] @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - Awaitable[empty_pb2.Empty]]: + 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. @@ -352,15 +358,13 @@ def delete_version(self) -> Callable[ # 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', + 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'] + return self._stubs["delete_version"] -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) +__all__ = ("VersionsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2beta1/types/__init__.py b/google/cloud/dialogflow_v2beta1/types/__init__.py index 1b5381fee..efe17b293 100644 --- a/google/cloud/dialogflow_v2beta1/types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .agent import ( Agent, DeleteAgentRequest, @@ -125,9 +123,21 @@ UpdateEntityTypeRequest, ) from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, ListEnvironmentsRequest, ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, ) from .gcs import ( GcsSource, @@ -219,6 +229,15 @@ ValidationError, ValidationResult, ) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) from .webhook import ( OriginalDetectIntentRequest, WebhookRequest, @@ -319,9 +338,19 @@ "ListEntityTypesRequest", "ListEntityTypesResponse", "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", "GcsSource", "GcsSources", "HumanAgentAssistantEvent", @@ -398,6 +427,13 @@ "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", diff --git a/google/cloud/dialogflow_v2beta1/types/agent.py b/google/cloud/dialogflow_v2beta1/types/agent.py index 980d7cb91..fc51cfd93 100644 --- a/google/cloud/dialogflow_v2beta1/types/agent.py +++ b/google/cloud/dialogflow_v2beta1/types/agent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -135,28 +132,17 @@ class Tier(proto.Enum): TIER_ENTERPRISE = 2 TIER_ENTERPRISE_PLUS = 3 - parent = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - default_language_code = proto.Field(proto.STRING, number=3) - - supported_language_codes = proto.RepeatedField(proto.STRING, number=4) - - time_zone = proto.Field(proto.STRING, number=5) - - description = proto.Field(proto.STRING, number=6) - - avatar_uri = proto.Field(proto.STRING, number=7) - - enable_logging = proto.Field(proto.BOOL, number=8) - + parent = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + default_language_code = proto.Field(proto.STRING, number=3,) + supported_language_codes = proto.RepeatedField(proto.STRING, number=4,) + time_zone = proto.Field(proto.STRING, number=5,) + description = proto.Field(proto.STRING, number=6,) + avatar_uri = proto.Field(proto.STRING, number=7,) + enable_logging = proto.Field(proto.BOOL, number=8,) match_mode = proto.Field(proto.ENUM, number=9, enum=MatchMode,) - - classification_threshold = proto.Field(proto.FLOAT, number=10) - + classification_threshold = proto.Field(proto.FLOAT, number=10,) api_version = proto.Field(proto.ENUM, number=14, enum=ApiVersion,) - tier = proto.Field(proto.ENUM, number=15, enum=Tier,) @@ -171,7 +157,7 @@ class GetAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SetAgentRequest(proto.Message): @@ -187,8 +173,9 @@ class SetAgentRequest(proto.Message): """ agent = proto.Field(proto.MESSAGE, number=1, message="Agent",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteAgentRequest(proto.Message): @@ -202,12 +189,11 @@ class DeleteAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SubAgent(proto.Message): r"""Contains basic configuration for a sub-agent. - Attributes: project (str): Required. The project of this agent. Format: @@ -219,9 +205,8 @@ class SubAgent(proto.Message): draft environment if ``environment`` is not set. """ - project = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) + project = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) class SearchAgentsRequest(proto.Message): @@ -242,11 +227,9 @@ class SearchAgentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class SearchAgentsResponse(proto.Message): @@ -268,8 +251,7 @@ def raw_page(self): return self agents = proto.RepeatedField(proto.MESSAGE, number=1, message="Agent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class TrainAgentRequest(proto.Message): @@ -283,7 +265,7 @@ class TrainAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -303,9 +285,8 @@ class ExportAgentRequest(proto.Message): the serialized agent is returned inline. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) class ExportAgentResponse(proto.Message): @@ -321,9 +302,8 @@ class ExportAgentResponse(proto.Message): Zip compressed raw byte content for agent. """ - agent_uri = proto.Field(proto.STRING, number=1, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=2, oneof="agent") + agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=2, oneof="agent",) class ImportAgentRequest(proto.Message): @@ -343,11 +323,9 @@ class ImportAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) class RestoreAgentRequest(proto.Message): @@ -367,11 +345,9 @@ class RestoreAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) class GetValidationResultRequest(proto.Message): @@ -392,9 +368,8 @@ class GetValidationResultRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/answer_record.py b/google/cloud/dialogflow_v2beta1/types/answer_record.py index 3661084a4..b645483eb 100644 --- a/google/cloud/dialogflow_v2beta1/types/answer_record.py +++ b/google/cloud/dialogflow_v2beta1/types/answer_record.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -84,10 +81,8 @@ class AnswerRecord(proto.Message): assistant. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) answer_feedback = proto.Field(proto.MESSAGE, number=3, message="AnswerFeedback",) - agent_assistant_record = proto.Field( proto.MESSAGE, number=4, oneof="record", message="AgentAssistantRecord", ) @@ -95,7 +90,6 @@ class AnswerRecord(proto.Message): class AgentAssistantRecord(proto.Message): r"""Represents a record of a human agent assistant answer. - Attributes: article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): Output only. The article suggestion answer. @@ -106,7 +100,6 @@ class AgentAssistantRecord(proto.Message): article_suggestion_answer = proto.Field( proto.MESSAGE, number=5, oneof="answer", message=participant.ArticleAnswer, ) - faq_answer = proto.Field( proto.MESSAGE, number=6, oneof="answer", message=participant.FaqAnswer, ) @@ -143,26 +136,22 @@ class CorrectnessLevel(proto.Enum): FULLY_CORRECT = 3 correctness_level = proto.Field(proto.ENUM, number=1, enum=CorrectnessLevel,) - agent_assistant_detail_feedback = proto.Field( proto.MESSAGE, number=2, oneof="detail_feedback", message="AgentAssistantFeedback", ) - - clicked = proto.Field(proto.BOOL, number=3) - - click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - displayed = proto.Field(proto.BOOL, number=4) - - display_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + clicked = proto.Field(proto.BOOL, number=3,) + click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + displayed = proto.Field(proto.BOOL, number=4,) + display_time = proto.Field( + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, + ) class AgentAssistantFeedback(proto.Message): r"""Detail feedback of Agent Assistant result. - Attributes: answer_relevance (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.AnswerRelevance): Optional. Whether or not the suggested answer is relevant. @@ -218,7 +207,6 @@ class DocumentEfficiency(proto.Enum): class SummarizationFeedback(proto.Message): r"""Feedback for conversation summarization. - Attributes: start_timestamp (google.protobuf.timestamp_pb2.Timestamp): Timestamp when composing of the summary @@ -230,21 +218,16 @@ class SummarizationFeedback(proto.Message): """ start_timestamp = proto.Field( - proto.MESSAGE, number=1, message=timestamp.Timestamp, + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) - submit_timestamp = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - - summary_text = proto.Field(proto.STRING, number=3) + summary_text = proto.Field(proto.STRING, number=3,) answer_relevance = proto.Field(proto.ENUM, number=1, enum=AnswerRelevance,) - document_correctness = proto.Field(proto.ENUM, number=2, enum=DocumentCorrectness,) - document_efficiency = proto.Field(proto.ENUM, number=3, enum=DocumentEfficiency,) - summarization_feedback = proto.Field( proto.MESSAGE, number=4, message=SummarizationFeedback, ) @@ -260,7 +243,7 @@ class GetAnswerRecordRequest(proto.Message): ``projects//locations//answerRecords/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListAnswerRecordsRequest(proto.Message): @@ -284,11 +267,9 @@ class ListAnswerRecordsRequest(proto.Message): listing on the next page. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListAnswerRecordsResponse(proto.Message): @@ -313,8 +294,7 @@ def raw_page(self): answer_records = proto.RepeatedField( proto.MESSAGE, number=1, message="AnswerRecord", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateAnswerRecordRequest(proto.Message): @@ -330,8 +310,9 @@ class UpdateAnswerRecordRequest(proto.Message): """ answer_record = proto.Field(proto.MESSAGE, number=1, message="AnswerRecord",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/audio_config.py b/google/cloud/dialogflow_v2beta1/types/audio_config.py index fda8a8e73..737f9c059 100644 --- a/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ b/google/cloud/dialogflow_v2beta1/types/audio_config.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -153,14 +150,12 @@ class SpeechContext(proto.Message): binary search. """ - phrases = proto.RepeatedField(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=2) + phrases = proto.RepeatedField(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=2,) class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -187,13 +182,10 @@ class SpeechWordInfo(proto.Message): also not rely on it to always be provided. """ - word = proto.Field(proto.STRING, number=3) - - start_offset = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_offset = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - confidence = proto.Field(proto.FLOAT, number=4) + word = proto.Field(proto.STRING, number=3,) + start_offset = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_offset = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + confidence = proto.Field(proto.FLOAT, number=4,) class InputAudioConfig(proto.Message): @@ -280,31 +272,21 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) speech_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message="SpeechContext", ) - - model = proto.Field(proto.STRING, number=7) - + model = proto.Field(proto.STRING, number=7,) model_variant = proto.Field(proto.ENUM, number=10, enum="SpeechModelVariant",) - - single_utterance = proto.Field(proto.BOOL, number=8) - - disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14) + single_utterance = proto.Field(proto.BOOL, number=8,) + disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14,) class VoiceSelectionParams(proto.Message): r"""Description of which voice to use for speech synthesis. - Attributes: name (str): Optional. The name of the voice. If not set, the service @@ -326,14 +308,12 @@ class VoiceSelectionParams(proto.Message): gender rather than failing the request. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) ssml_gender = proto.Field(proto.ENUM, number=2, enum="SsmlVoiceGender",) class SynthesizeSpeechConfig(proto.Message): r"""Configuration of how speech should be synthesized. - Attributes: speaking_rate (float): Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 @@ -367,14 +347,10 @@ class SynthesizeSpeechConfig(proto.Message): synthesized audio. """ - speaking_rate = proto.Field(proto.DOUBLE, number=1) - - pitch = proto.Field(proto.DOUBLE, number=2) - - volume_gain_db = proto.Field(proto.DOUBLE, number=3) - - effects_profile_id = proto.RepeatedField(proto.STRING, number=5) - + speaking_rate = proto.Field(proto.DOUBLE, number=1,) + pitch = proto.Field(proto.DOUBLE, number=2,) + volume_gain_db = proto.Field(proto.DOUBLE, number=3,) + effects_profile_id = proto.RepeatedField(proto.STRING, number=5,) voice = proto.Field(proto.MESSAGE, number=4, message="VoiceSelectionParams",) @@ -403,9 +379,7 @@ class OutputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="OutputAudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) synthesize_speech_config = proto.Field( proto.MESSAGE, number=3, message="SynthesizeSpeechConfig", ) @@ -413,7 +387,6 @@ class OutputAudioConfig(proto.Message): class TelephonyDtmfEvents(proto.Message): r"""A wrapper of repeated TelephonyDtmf digits. - Attributes: dtmf_events (Sequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): A sequence of TelephonyDtmf digits. diff --git a/google/cloud/dialogflow_v2beta1/types/context.py b/google/cloud/dialogflow_v2beta1/types/context.py index d0179a6a2..8b4d02a29 100644 --- a/google/cloud/dialogflow_v2beta1/types/context.py +++ b/google/cloud/dialogflow_v2beta1/types/context.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -108,11 +105,9 @@ class Context(proto.Message): Else: parameter value """ - name = proto.Field(proto.STRING, number=1) - - lifespan_count = proto.Field(proto.INT32, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + name = proto.Field(proto.STRING, number=1,) + lifespan_count = proto.Field(proto.INT32, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) class ListContextsRequest(proto.Message): @@ -142,11 +137,9 @@ class ListContextsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListContextsResponse(proto.Message): @@ -168,8 +161,7 @@ def raw_page(self): return self contexts = proto.RepeatedField(proto.MESSAGE, number=1, message="Context",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetContextRequest(proto.Message): @@ -191,7 +183,7 @@ class GetContextRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateContextRequest(proto.Message): @@ -216,8 +208,7 @@ class CreateContextRequest(proto.Message): Required. The context to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) context = proto.Field(proto.MESSAGE, number=2, message="Context",) @@ -234,8 +225,9 @@ class UpdateContextRequest(proto.Message): """ context = proto.Field(proto.MESSAGE, number=1, message="Context",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteContextRequest(proto.Message): @@ -258,7 +250,7 @@ class DeleteContextRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteAllContextsRequest(proto.Message): @@ -281,7 +273,7 @@ class DeleteAllContextsRequest(proto.Message): specified, we assume default '-' user. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/conversation.py b/google/cloud/dialogflow_v2beta1/types/conversation.py index 11ffff26c..ba8089cf0 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -105,21 +102,15 @@ class ConversationStage(proto.Enum): VIRTUAL_AGENT_STAGE = 1 HUMAN_ASSIST_STAGE = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) lifecycle_state = proto.Field(proto.ENUM, number=2, enum=LifecycleState,) - - conversation_profile = proto.Field(proto.STRING, number=3) - + conversation_profile = proto.Field(proto.STRING, number=3,) phone_number = proto.Field( proto.MESSAGE, number=4, message="ConversationPhoneNumber", ) - conversation_stage = proto.Field(proto.ENUM, number=7, enum=ConversationStage,) - - start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) class ConversationPhoneNumber(proto.Message): @@ -132,7 +123,7 @@ class ConversationPhoneNumber(proto.Message): this conversation. """ - phone_number = proto.Field(proto.STRING, number=3) + phone_number = proto.Field(proto.STRING, number=3,) class CreateConversationRequest(proto.Message): @@ -162,11 +153,9 @@ class CreateConversationRequest(proto.Message): a project to better ensure uniqueness. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation = proto.Field(proto.MESSAGE, number=2, message="Conversation",) - - conversation_id = proto.Field(proto.STRING, number=3) + conversation_id = proto.Field(proto.STRING, number=3,) class ListConversationsRequest(proto.Message): @@ -208,13 +197,10 @@ class ListConversationsRequest(proto.Message): Filtering `__. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListConversationsResponse(proto.Message): @@ -238,8 +224,7 @@ def raw_page(self): conversations = proto.RepeatedField( proto.MESSAGE, number=1, message="Conversation", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationRequest(proto.Message): @@ -252,7 +237,7 @@ class GetConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CompleteConversationRequest(proto.Message): @@ -266,7 +251,7 @@ class CompleteConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateMessageRequest(proto.Message): @@ -284,8 +269,7 @@ class CreateMessageRequest(proto.Message): is required. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) message = proto.Field(proto.MESSAGE, number=2, message=participant.Message,) @@ -305,8 +289,7 @@ class BatchCreateMessagesRequest(proto.Message): [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) requests = proto.RepeatedField( proto.MESSAGE, number=2, message="CreateMessageRequest", ) @@ -341,7 +324,7 @@ class ListMessagesRequest(proto.Message): supported. ``create_time`` only support milliseconds accuracy. E.g., ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > 2017-01-15T01:30:15.01Z``. + ``create_time > "2017-01-15T01:30:15.01Z"``. For more information about filtering, see `API Filtering `__. @@ -354,13 +337,10 @@ class ListMessagesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListMessagesResponse(proto.Message): @@ -386,8 +366,7 @@ def raw_page(self): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=participant.Message, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/conversation_event.py b/google/cloud/dialogflow_v2beta1/types/conversation_event.py index a9091e3af..dee158441 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation_event.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import participant -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -54,12 +51,9 @@ class Type(proto.Enum): NEW_MESSAGE = 5 UNRECOVERABLE_ERROR = 4 - conversation = proto.Field(proto.STRING, number=1) - + conversation = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - error_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - + error_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) new_message_payload = proto.Field( proto.MESSAGE, number=4, oneof="payload", message=participant.Message, ) diff --git a/google/cloud/dialogflow_v2beta1/types/conversation_profile.py b/google/cloud/dialogflow_v2beta1/types/conversation_profile.py index 4d1c17775..0e9d1a396 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation_profile.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation_profile.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -68,6 +65,8 @@ class ConversationProfile(proto.Message): with this profile. human_agent_handoff_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig): Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): Configuration for publishing conversation lifecycle events. @@ -87,46 +86,38 @@ class ConversationProfile(proto.Message): for all non en-us languages. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - create_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=12, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=11, message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, number=12, message=timestamp_pb2.Timestamp, + ) automated_agent_config = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentConfig", ) - human_agent_assistant_config = proto.Field( proto.MESSAGE, number=4, message="HumanAgentAssistantConfig", ) - human_agent_handoff_config = proto.Field( proto.MESSAGE, number=5, message="HumanAgentHandoffConfig", ) - notification_config = proto.Field( proto.MESSAGE, number=6, message="NotificationConfig", ) - logging_config = proto.Field(proto.MESSAGE, number=7, message="LoggingConfig",) - new_message_event_notification_config = proto.Field( proto.MESSAGE, number=8, message="NotificationConfig", ) - stt_config = proto.Field( proto.MESSAGE, number=9, message=audio_config.SpeechToTextConfig, ) - - language_code = proto.Field(proto.STRING, number=10) + language_code = proto.Field(proto.STRING, number=10,) class AutomatedAgentConfig(proto.Message): r"""Defines the Automated Agent to connect to a conversation. - Attributes: agent (str): Required. ID of the Dialogflow agent environment to use. @@ -149,7 +140,7 @@ class AutomatedAgentConfig(proto.Message): environment is used. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class HumanAgentAssistantConfig(proto.Message): @@ -166,13 +157,14 @@ class HumanAgentAssistantConfig(proto.Message): end_user_suggestion_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionConfig): Configuration for agent assistance of end user participant. + Currently, this feature is not general + available, please contact Google to get access. message_analysis_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.MessageAnalysisConfig): Configuration for message analysis. """ class SuggestionTriggerSettings(proto.Message): r"""Settings of suggestion trigger. - Attributes: no_small_talk (bool): Do not trigger if last utterance is small @@ -182,13 +174,11 @@ class SuggestionTriggerSettings(proto.Message): utterance is END_USER. """ - no_small_talk = proto.Field(proto.BOOL, number=1) - - only_end_user = proto.Field(proto.BOOL, number=2) + no_small_talk = proto.Field(proto.BOOL, number=1,) + only_end_user = proto.Field(proto.BOOL, number=2,) class SuggestionFeatureConfig(proto.Message): r"""Config for suggestion features. - Attributes: suggestion_feature (google.cloud.dialogflow_v2beta1.types.SuggestionFeature): The suggestion feature. @@ -212,21 +202,17 @@ class SuggestionFeatureConfig(proto.Message): suggestion_feature = proto.Field( proto.MESSAGE, number=5, message=participant.SuggestionFeature, ) - - enable_event_based_suggestion = proto.Field(proto.BOOL, number=3) - + enable_event_based_suggestion = proto.Field(proto.BOOL, number=3,) suggestion_trigger_settings = proto.Field( proto.MESSAGE, number=10, message="HumanAgentAssistantConfig.SuggestionTriggerSettings", ) - query_config = proto.Field( proto.MESSAGE, number=6, message="HumanAgentAssistantConfig.SuggestionQueryConfig", ) - conversation_model_config = proto.Field( proto.MESSAGE, number=7, @@ -235,7 +221,6 @@ class SuggestionFeatureConfig(proto.Message): class SuggestionConfig(proto.Message): r"""Detail human agent assistant config. - Attributes: feature_configs (Sequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): Configuration of different suggestion @@ -260,12 +245,10 @@ class SuggestionConfig(proto.Message): number=2, message="HumanAgentAssistantConfig.SuggestionFeatureConfig", ) - - group_suggestion_responses = proto.Field(proto.BOOL, number=3) + group_suggestion_responses = proto.Field(proto.BOOL, number=3,) class SuggestionQueryConfig(proto.Message): r"""Config for suggestion query. - Attributes: knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, @@ -320,7 +303,7 @@ class KnowledgeBaseQuerySource(proto.Message): Currently, only one knowledge base is supported. """ - knowledge_bases = proto.RepeatedField(proto.STRING, number=1) + knowledge_bases = proto.RepeatedField(proto.STRING, number=1,) class DocumentQuerySource(proto.Message): r"""Document source settings. @@ -334,7 +317,7 @@ class DocumentQuerySource(proto.Message): Currently, only one document is supported. """ - documents = proto.RepeatedField(proto.STRING, number=1) + documents = proto.RepeatedField(proto.STRING, number=1,) class DialogflowQuerySource(proto.Message): r"""Dialogflow source setting. @@ -350,7 +333,7 @@ class DialogflowQuerySource(proto.Message): project. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class ContextFilterSettings(proto.Message): r"""Settings that determine how to filter recent conversation @@ -369,11 +352,9 @@ class ContextFilterSettings(proto.Message): are dropped. """ - drop_handoff_messages = proto.Field(proto.BOOL, number=1) - - drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2) - - drop_ivr_messages = proto.Field(proto.BOOL, number=3) + drop_handoff_messages = proto.Field(proto.BOOL, number=1,) + drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2,) + drop_ivr_messages = proto.Field(proto.BOOL, number=3,) knowledge_base_query_source = proto.Field( proto.MESSAGE, @@ -381,25 +362,20 @@ class ContextFilterSettings(proto.Message): oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource", ) - document_query_source = proto.Field( proto.MESSAGE, number=2, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource", ) - dialogflow_query_source = proto.Field( proto.MESSAGE, number=3, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource", ) - - max_results = proto.Field(proto.INT32, number=4) - - confidence_threshold = proto.Field(proto.FLOAT, number=5) - + max_results = proto.Field(proto.INT32, number=4,) + confidence_threshold = proto.Field(proto.FLOAT, number=5,) context_filter_settings = proto.Field( proto.MESSAGE, number=7, @@ -413,11 +389,11 @@ class ConversationModelConfig(proto.Message): Attributes: model (str): - Required. Conversation model resource name. Format: + Conversation model resource name. Format: ``projects//conversationModels/``. """ - model = proto.Field(proto.STRING, number=1) + model = proto.Field(proto.STRING, number=1,) class MessageAnalysisConfig(proto.Message): r"""Configuration for analyses to run on each conversation @@ -429,6 +405,9 @@ class MessageAnalysisConfig(proto.Message): assist stage `__. If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. enable_sentiment_analysis (bool): Enable sentiment analysis in conversation messages on `agent assist @@ -454,22 +433,18 @@ class MessageAnalysisConfig(proto.Message): [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ConversationEvent.new_message_payload]. """ - enable_entity_extraction = proto.Field(proto.BOOL, number=2) - - enable_sentiment_analysis = proto.Field(proto.BOOL, number=3) + enable_entity_extraction = proto.Field(proto.BOOL, number=2,) + enable_sentiment_analysis = proto.Field(proto.BOOL, number=3,) notification_config = proto.Field( proto.MESSAGE, number=2, message="NotificationConfig", ) - human_agent_suggestion_config = proto.Field( proto.MESSAGE, number=3, message=SuggestionConfig, ) - end_user_suggestion_config = proto.Field( proto.MESSAGE, number=4, message=SuggestionConfig, ) - message_analysis_config = proto.Field( proto.MESSAGE, number=5, message=MessageAnalysisConfig, ) @@ -478,6 +453,8 @@ class MessageAnalysisConfig(proto.Message): class HumanAgentHandoffConfig(proto.Message): r"""Defines the hand off to a live agent, typically on which external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. Attributes: live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): @@ -497,11 +474,10 @@ class LivePersonConfig(proto.Message): you input at the login page. """ - account_number = proto.Field(proto.STRING, number=1) + account_number = proto.Field(proto.STRING, number=1,) class SalesforceLiveAgentConfig(proto.Message): r"""Configuration specific to Salesforce Live Agent. - Attributes: organization_id (str): Required. The organization ID of the @@ -518,18 +494,14 @@ class SalesforceLiveAgentConfig(proto.Message): fill in d.la4-c2-phx.salesforceliveagent.com. """ - organization_id = proto.Field(proto.STRING, number=1) - - deployment_id = proto.Field(proto.STRING, number=2) - - button_id = proto.Field(proto.STRING, number=3) - - endpoint_domain = proto.Field(proto.STRING, number=4) + organization_id = proto.Field(proto.STRING, number=1,) + deployment_id = proto.Field(proto.STRING, number=2,) + button_id = proto.Field(proto.STRING, number=3,) + endpoint_domain = proto.Field(proto.STRING, number=4,) live_person_config = proto.Field( proto.MESSAGE, number=1, oneof="agent_service", message=LivePersonConfig, ) - salesforce_live_agent_config = proto.Field( proto.MESSAGE, number=2, @@ -540,7 +512,6 @@ class SalesforceLiveAgentConfig(proto.Message): class NotificationConfig(proto.Message): r"""Defines notification behavior. - Attributes: topic (str): Name of the Pub/Sub topic to publish conversation events @@ -567,14 +538,12 @@ class MessageFormat(proto.Enum): PROTO = 1 JSON = 2 - topic = proto.Field(proto.STRING, number=1) - + topic = proto.Field(proto.STRING, number=1,) message_format = proto.Field(proto.ENUM, number=2, enum=MessageFormat,) class LoggingConfig(proto.Message): r"""Defines logging behavior for conversation lifecycle events. - Attributes: enable_stackdriver_logging (bool): Whether to log conversation events like @@ -584,7 +553,7 @@ class LoggingConfig(proto.Message): protos. """ - enable_stackdriver_logging = proto.Field(proto.BOOL, number=3) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=3,) class ListConversationProfilesRequest(proto.Message): @@ -604,11 +573,9 @@ class ListConversationProfilesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListConversationProfilesResponse(proto.Message): @@ -633,8 +600,7 @@ def raw_page(self): conversation_profiles = proto.RepeatedField( proto.MESSAGE, number=1, message="ConversationProfile", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationProfileRequest(proto.Message): @@ -648,7 +614,7 @@ class GetConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateConversationProfileRequest(proto.Message): @@ -663,8 +629,7 @@ class CreateConversationProfileRequest(proto.Message): Required. The conversation profile to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation_profile = proto.Field( proto.MESSAGE, number=2, message="ConversationProfile", ) @@ -685,8 +650,9 @@ class UpdateConversationProfileRequest(proto.Message): conversation_profile = proto.Field( proto.MESSAGE, number=1, message="ConversationProfile", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteConversationProfileRequest(proto.Message): @@ -703,7 +669,7 @@ class DeleteConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/document.py b/google/cloud/dialogflow_v2beta1/types/document.py index 3a90e221e..4597aeb95 100644 --- a/google/cloud/dialogflow_v2beta1/types/document.py +++ b/google/cloud/dialogflow_v2beta1/types/document.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import gcs -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -128,7 +125,6 @@ class KnowledgeType(proto.Enum): class ReloadStatus(proto.Message): r"""The status of a reload attempt. - Attributes: time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time of a reload attempt. @@ -140,29 +136,19 @@ class ReloadStatus(proto.Message): or the initial load. """ - time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) + time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) knowledge_types = proto.RepeatedField(proto.ENUM, number=4, enum=KnowledgeType,) - - content_uri = proto.Field(proto.STRING, number=5, oneof="source") - - content = proto.Field(proto.STRING, number=6, oneof="source") - - raw_content = proto.Field(proto.BYTES, number=9, oneof="source") - - enable_auto_reload = proto.Field(proto.BOOL, number=11) - + content_uri = proto.Field(proto.STRING, number=5, oneof="source",) + content = proto.Field(proto.STRING, number=6, oneof="source",) + raw_content = proto.Field(proto.BYTES, number=9, oneof="source",) + enable_auto_reload = proto.Field(proto.BOOL, number=11,) latest_reload_status = proto.Field(proto.MESSAGE, number=12, message=ReloadStatus,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=7) + metadata = proto.MapField(proto.STRING, proto.STRING, number=7,) class GetDocumentRequest(proto.Message): @@ -175,7 +161,7 @@ class GetDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListDocumentsRequest(proto.Message): @@ -219,13 +205,10 @@ class ListDocumentsRequest(proto.Message): Filtering `__. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListDocumentsResponse(proto.Message): @@ -246,8 +229,7 @@ def raw_page(self): return self documents = proto.RepeatedField(proto.MESSAGE, number=1, message="Document",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateDocumentRequest(proto.Message): @@ -267,11 +249,9 @@ class CreateDocumentRequest(proto.Message): source is Google Cloud Storage URI. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) document = proto.Field(proto.MESSAGE, number=2, message="Document",) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=3) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=3,) class ImportDocumentsRequest(proto.Message): @@ -299,22 +279,18 @@ class ImportDocumentsRequest(proto.Message): source is Google Cloud Storage URI. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message=gcs.GcsSources, ) - document_template = proto.Field( proto.MESSAGE, number=3, message="ImportDocumentTemplate", ) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4,) class ImportDocumentTemplate(proto.Message): r"""The template used for importing documents. - Attributes: mime_type (str): Required. The MIME type of the document. @@ -329,13 +305,11 @@ class ImportDocumentTemplate(proto.Message): ``value`` of the metadata is 1024 bytes. """ - mime_type = proto.Field(proto.STRING, number=1) - + mime_type = proto.Field(proto.STRING, number=1,) knowledge_types = proto.RepeatedField( proto.ENUM, number=2, enum="Document.KnowledgeType", ) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=3) + metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) class ImportDocumentsResponse(proto.Message): @@ -348,7 +322,7 @@ class ImportDocumentsResponse(proto.Message): any other warnings. """ - warnings = proto.RepeatedField(proto.MESSAGE, number=1, message=gr_status.Status,) + warnings = proto.RepeatedField(proto.MESSAGE, number=1, message=status_pb2.Status,) class DeleteDocumentRequest(proto.Message): @@ -361,7 +335,7 @@ class DeleteDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateDocumentRequest(proto.Message): @@ -378,8 +352,9 @@ class UpdateDocumentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class KnowledgeOperationMetadata(proto.Message): @@ -420,13 +395,11 @@ class ReloadDocumentRequest(proto.Message): source is Google Cloud Storage URI. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=3, oneof="source", message=gcs.GcsSource, ) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/entity_type.py b/google/cloud/dialogflow_v2beta1/types/entity_type.py index e395607b1..1143c6b55 100644 --- a/google/cloud/dialogflow_v2beta1/types/entity_type.py +++ b/google/cloud/dialogflow_v2beta1/types/entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -100,7 +97,6 @@ class AutoExpansionMode(proto.Enum): class Entity(proto.Message): r"""An **entity entry** for an associated entity type. - Attributes: value (str): Required. The primary value associated with this entity @@ -126,21 +122,15 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) kind = proto.Field(proto.ENUM, number=3, enum=Kind,) - auto_expansion_mode = proto.Field(proto.ENUM, number=4, enum=AutoExpansionMode,) - entities = proto.RepeatedField(proto.MESSAGE, number=6, message=Entity,) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) class ListEntityTypesRequest(proto.Message): @@ -169,13 +159,10 @@ class ListEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListEntityTypesResponse(proto.Message): @@ -198,8 +185,7 @@ def raw_page(self): return self entity_types = proto.RepeatedField(proto.MESSAGE, number=1, message="EntityType",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEntityTypeRequest(proto.Message): @@ -220,9 +206,8 @@ class GetEntityTypeRequest(proto.Message): data `__. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateEntityTypeRequest(proto.Message): @@ -246,11 +231,9 @@ class CreateEntityTypeRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type = proto.Field(proto.MESSAGE, number=2, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateEntityTypeRequest(proto.Message): @@ -272,10 +255,10 @@ class UpdateEntityTypeRequest(proto.Message): """ entity_type = proto.Field(proto.MESSAGE, number=1, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteEntityTypeRequest(proto.Message): @@ -291,7 +274,7 @@ class DeleteEntityTypeRequest(proto.Message): - ``projects//locations//agent/entityTypes/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateEntityTypesRequest(proto.Message): @@ -325,19 +308,17 @@ class BatchUpdateEntityTypesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type_batch_uri = proto.Field( - proto.STRING, number=2, oneof="entity_type_batch" + proto.STRING, number=2, oneof="entity_type_batch", ) - entity_type_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="entity_type_batch", message="EntityTypeBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) class BatchUpdateEntityTypesResponse(proto.Message): @@ -369,9 +350,8 @@ class BatchDeleteEntityTypesRequest(proto.Message): point to the same agent as ``parent``. """ - parent = proto.Field(proto.STRING, number=1) - - entity_type_names = proto.RepeatedField(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entity_type_names = proto.RepeatedField(proto.STRING, number=2,) class BatchCreateEntitiesRequest(proto.Message): @@ -395,13 +375,11 @@ class BatchCreateEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class BatchUpdateEntitiesRequest(proto.Message): @@ -428,15 +406,14 @@ class BatchUpdateEntitiesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) - - update_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=3,) + update_mask = proto.Field( + proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask, + ) class BatchDeleteEntitiesRequest(proto.Message): @@ -462,11 +439,9 @@ class BatchDeleteEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - - entity_values = proto.RepeatedField(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + entity_values = proto.RepeatedField(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) class EntityTypeBatch(proto.Message): diff --git a/google/cloud/dialogflow_v2beta1/types/environment.py b/google/cloud/dialogflow_v2beta1/types/environment.py index 9f5c887de..5ee003e2f 100644 --- a/google/cloud/dialogflow_v2beta1/types/environment.py +++ b/google/cloud/dialogflow_v2beta1/types/environment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.dialogflow.v2beta1", - manifest={"Environment", "ListEnvironmentsRequest", "ListEnvironmentsResponse",}, + manifest={ + "Environment", + "TextToSpeechSettings", + "ListEnvironmentsRequest", + "ListEnvironmentsResponse", + "GetEnvironmentRequest", + "CreateEnvironmentRequest", + "UpdateEnvironmentRequest", + "DeleteEnvironmentRequest", + "GetEnvironmentHistoryRequest", + "EnvironmentHistory", + }, ) @@ -74,6 +85,12 @@ class Environment(proto.Message): Output only. The last update time of this environment. This field is read-only, i.e., it cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. """ class State(proto.Enum): @@ -89,15 +106,58 @@ class State(proto.Enum): LOADING = 2 RUNNING = 3 - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + agent_version = proto.Field(proto.STRING, number=3,) + state = proto.Field(proto.ENUM, number=4, enum=State,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + text_to_speech_settings = proto.Field( + proto.MESSAGE, number=7, message="TextToSpeechSettings", + ) + fulfillment = proto.Field( + proto.MESSAGE, number=8, message=gcd_fulfillment.Fulfillment, + ) - description = proto.Field(proto.STRING, number=2) - agent_version = proto.Field(proto.STRING, number=3) +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. - state = proto.Field(proto.ENUM, number=4, enum=State,) + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2beta1.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + enable_text_to_speech = proto.Field(proto.BOOL, number=1,) + output_audio_encoding = proto.Field( + proto.ENUM, number=2, enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field(proto.INT32, number=3,) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) class ListEnvironmentsRequest(proto.Message): @@ -119,11 +179,9 @@ class ListEnvironmentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListEnvironmentsResponse(proto.Message): @@ -146,8 +204,160 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) + environment_id = proto.Field(proto.STRING, number=3,) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field(proto.BOOL, number=3,) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2beta1.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self - next_page_token = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entries = proto.RepeatedField(proto.MESSAGE, number=2, message=Entry,) + next_page_token = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py b/google/cloud/dialogflow_v2beta1/types/fulfillment.py similarity index 77% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py rename to google/cloud/dialogflow_v2beta1/types/fulfillment.py index 8a35fc7c4..a77f89e38 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py +++ b/google/cloud/dialogflow_v2beta1/types/fulfillment.py @@ -19,12 +19,8 @@ __protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Fulfillment', - 'GetFulfillmentRequest', - 'UpdateFulfillmentRequest', - }, + package="google.cloud.dialogflow.v2beta1", + manifest={"Fulfillment", "GetFulfillmentRequest", "UpdateFulfillmentRequest",}, ) @@ -90,27 +86,11 @@ class GenericWebService(proto.Message): configured by its uri as a regular web service now. """ - uri = proto.Field( - proto.STRING, - number=1, - ) - username = proto.Field( - proto.STRING, - number=2, - ) - password = proto.Field( - proto.STRING, - number=3, - ) - request_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - is_cloud_function = proto.Field( - proto.BOOL, - number=5, - ) + uri = proto.Field(proto.STRING, number=1,) + username = proto.Field(proto.STRING, number=2,) + password = proto.Field(proto.STRING, number=3,) + request_headers = proto.MapField(proto.STRING, proto.STRING, number=4,) + is_cloud_function = proto.Field(proto.BOOL, number=5,) class Feature(proto.Message): r"""Whether fulfillment is enabled for the specific feature. @@ -119,40 +99,21 @@ class Feature(proto.Message): The type of the feature that enabled for fulfillment. """ + class Type(proto.Enum): r"""The type of the feature.""" TYPE_UNSPECIFIED = 0 SMALLTALK = 1 - type_ = proto.Field( - proto.ENUM, - number=1, - enum='Fulfillment.Feature.Type', - ) + type_ = proto.Field(proto.ENUM, number=1, enum="Fulfillment.Feature.Type",) - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) generic_web_service = proto.Field( - proto.MESSAGE, - number=3, - oneof='fulfillment', - message=GenericWebService, - ) - enabled = proto.Field( - proto.BOOL, - number=4, - ) - features = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Feature, + proto.MESSAGE, number=3, oneof="fulfillment", message=GenericWebService, ) + enabled = proto.Field(proto.BOOL, number=4,) + features = proto.RepeatedField(proto.MESSAGE, number=5, message=Feature,) class GetFulfillmentRequest(proto.Message): @@ -167,10 +128,7 @@ class GetFulfillmentRequest(proto.Message): - ``projects//locations//agent/fulfillment`` """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) class UpdateFulfillmentRequest(proto.Message): @@ -186,15 +144,9 @@ class UpdateFulfillmentRequest(proto.Message): fields will be updated. """ - fulfillment = proto.Field( - proto.MESSAGE, - number=1, - message='Fulfillment', - ) + fulfillment = proto.Field(proto.MESSAGE, number=1, message="Fulfillment",) update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) diff --git a/google/cloud/dialogflow_v2beta1/types/gcs.py b/google/cloud/dialogflow_v2beta1/types/gcs.py index 17dd7573a..6905e49cc 100644 --- a/google/cloud/dialogflow_v2beta1/types/gcs.py +++ b/google/cloud/dialogflow_v2beta1/types/gcs.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class GcsSources(proto.Message): r"""Google Cloud Storage locations for the inputs. - Attributes: uris (Sequence[str]): Required. Google Cloud Storage URIs for the @@ -35,12 +32,11 @@ class GcsSources(proto.Message): use case. """ - uris = proto.RepeatedField(proto.STRING, number=2) + uris = proto.RepeatedField(proto.STRING, number=2,) class GcsSource(proto.Message): r"""Google Cloud Storage location for single input. - Attributes: uri (str): Required. The Google Cloud Storage URIs for @@ -50,7 +46,7 @@ class GcsSource(proto.Message): use case. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py b/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py index 66d6bf2c9..b66735d32 100644 --- a/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py +++ b/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant @@ -51,10 +48,8 @@ class HumanAgentAssistantEvent(proto.Message): sets to true. """ - conversation = proto.Field(proto.STRING, number=1) - - participant = proto.Field(proto.STRING, number=3) - + conversation = proto.Field(proto.STRING, number=1,) + participant = proto.Field(proto.STRING, number=3,) suggestion_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_participant.SuggestionResult, ) diff --git a/google/cloud/dialogflow_v2beta1/types/intent.py b/google/cloud/dialogflow_v2beta1/types/intent.py index 75dea97f7..3a1e868ec 100644 --- a/google/cloud/dialogflow_v2beta1/types/intent.py +++ b/google/cloud/dialogflow_v2beta1/types/intent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import context -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -195,7 +192,6 @@ class WebhookState(proto.Enum): class TrainingPhrase(proto.Message): r"""Represents an example that the agent is trained on. - Attributes: name (str): Output only. The unique identifier of this @@ -242,7 +238,6 @@ class Type(proto.Enum): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -263,27 +258,20 @@ class Part(proto.Message): part with the API, you must set this to true. """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - alias = proto.Field(proto.STRING, number=3) - - user_defined = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + alias = proto.Field(proto.STRING, number=3,) + user_defined = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum="Intent.TrainingPhrase.Type",) - parts = proto.RepeatedField( proto.MESSAGE, number=3, message="Intent.TrainingPhrase.Part", ) - - times_added_count = proto.Field(proto.INT32, number=4) + times_added_count = proto.Field(proto.INT32, number=4,) class Parameter(proto.Message): r"""Represents intent parameters. - Attributes: name (str): The unique identifier of this parameter. @@ -321,25 +309,17 @@ class Parameter(proto.Message): represents a list of values. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - value = proto.Field(proto.STRING, number=3) - - default_value = proto.Field(proto.STRING, number=4) - - entity_type_display_name = proto.Field(proto.STRING, number=5) - - mandatory = proto.Field(proto.BOOL, number=6) - - prompts = proto.RepeatedField(proto.STRING, number=7) - - is_list = proto.Field(proto.BOOL, number=8) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + value = proto.Field(proto.STRING, number=3,) + default_value = proto.Field(proto.STRING, number=4,) + entity_type_display_name = proto.Field(proto.STRING, number=5,) + mandatory = proto.Field(proto.BOOL, number=6,) + prompts = proto.RepeatedField(proto.STRING, number=7,) + is_list = proto.Field(proto.BOOL, number=8,) class Message(proto.Message): r"""Corresponds to the ``Response`` field in the Dialogflow console. - Attributes: text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): Returns a text response. @@ -413,18 +393,16 @@ class Platform(proto.Enum): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Optional. The collection of the agent's responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class Image(proto.Message): r"""The image response message. - Attributes: image_uri (str): Optional. The public URI to an image file. @@ -434,13 +412,11 @@ class Image(proto.Message): is set for CarouselSelect. """ - image_uri = proto.Field(proto.STRING, number=1) - - accessibility_text = proto.Field(proto.STRING, number=2) + image_uri = proto.Field(proto.STRING, number=1,) + accessibility_text = proto.Field(proto.STRING, number=2,) class QuickReplies(proto.Message): r"""The quick replies response message. - Attributes: title (str): Optional. The title of the collection of @@ -449,13 +425,11 @@ class QuickReplies(proto.Message): Optional. The collection of quick replies. """ - title = proto.Field(proto.STRING, number=1) - - quick_replies = proto.RepeatedField(proto.STRING, number=2) + title = proto.Field(proto.STRING, number=1,) + quick_replies = proto.RepeatedField(proto.STRING, number=2,) class Card(proto.Message): r"""The card response message. - Attributes: title (str): Optional. The title of the card. @@ -470,7 +444,6 @@ class Card(proto.Message): class Button(proto.Message): r"""Optional. Contains information about a button. - Attributes: text (str): Optional. The text to show on the button. @@ -479,23 +452,18 @@ class Button(proto.Message): Dialogflow API or a URI to open. """ - text = proto.Field(proto.STRING, number=1) - - postback = proto.Field(proto.STRING, number=2) - - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - image_uri = proto.Field(proto.STRING, number=3) + text = proto.Field(proto.STRING, number=1,) + postback = proto.Field(proto.STRING, number=2,) + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + image_uri = proto.Field(proto.STRING, number=3,) buttons = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.Card.Button", ) class SimpleResponse(proto.Message): r"""The simple response message containing speech or text. - Attributes: text_to_speech (str): One of text_to_speech or ssml must be provided. The plain @@ -508,11 +476,9 @@ class SimpleResponse(proto.Message): Optional. The text to display. """ - text_to_speech = proto.Field(proto.STRING, number=1) - - ssml = proto.Field(proto.STRING, number=2) - - display_text = proto.Field(proto.STRING, number=3) + text_to_speech = proto.Field(proto.STRING, number=1,) + ssml = proto.Field(proto.STRING, number=2,) + display_text = proto.Field(proto.STRING, number=3,) class SimpleResponses(proto.Message): r"""The collection of simple response candidates. This message in @@ -531,7 +497,6 @@ class SimpleResponses(proto.Message): class BasicCard(proto.Message): r"""The basic card message. Useful for displaying information. - Attributes: title (str): Optional. The title of the card. @@ -548,7 +513,6 @@ class BasicCard(proto.Message): class Button(proto.Message): r"""The button object that appears at the bottom of a card. - Attributes: title (str): Required. The title of the button. @@ -559,32 +523,26 @@ class Button(proto.Message): class OpenUriAction(proto.Message): r"""Opens the given URI. - Attributes: uri (str): Required. The HTTP or HTTPS scheme URI. """ - uri = proto.Field(proto.STRING, number=1) - - title = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + title = proto.Field(proto.STRING, number=1,) open_uri_action = proto.Field( proto.MESSAGE, number=2, message="Intent.Message.BasicCard.Button.OpenUriAction", ) - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - formatted_text = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + formatted_text = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.BasicCard.Button", ) @@ -599,11 +557,10 @@ class Suggestion(proto.Message): suggestion chip. """ - title = proto.Field(proto.STRING, number=1) + title = proto.Field(proto.STRING, number=1,) class Suggestions(proto.Message): r"""The collection of suggestions. - Attributes: suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): Required. The list of suggested replies. @@ -626,13 +583,11 @@ class LinkOutSuggestion(proto.Message): when the user taps the suggestion chip. """ - destination_name = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) + destination_name = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) class ListSelect(proto.Message): r"""The card for presenting a list of options to select from. - Attributes: title (str): Optional. The overall title of the list. @@ -644,7 +599,6 @@ class ListSelect(proto.Message): class Item(proto.Message): r"""An item in the list. - Attributes: info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): Required. Additional information about this @@ -660,26 +614,20 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - title = proto.Field(proto.STRING, number=1) - + title = proto.Field(proto.STRING, number=1,) items = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.ListSelect.Item", ) - - subtitle = proto.Field(proto.STRING, number=3) + subtitle = proto.Field(proto.STRING, number=3,) class CarouselSelect(proto.Message): r"""The card for presenting a carousel of options to select from. - Attributes: items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): Required. Carousel items. @@ -687,7 +635,6 @@ class CarouselSelect(proto.Message): class Item(proto.Message): r"""An item in the carousel. - Attributes: info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): Required. Additional info about the option @@ -703,11 +650,8 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) @@ -729,13 +673,11 @@ class SelectItemInfo(proto.Message): used to trigger this item in dialog. """ - key = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + key = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class TelephonyPlayAudio(proto.Message): r"""Plays audio from a file in Telephony Gateway. - Attributes: audio_uri (str): Required. URI to a Google Cloud Storage object containing @@ -755,7 +697,7 @@ class TelephonyPlayAudio(proto.Message): ``TelephonySynthesizeSpeech`` message with SSML. """ - audio_uri = proto.Field(proto.STRING, number=1) + audio_uri = proto.Field(proto.STRING, number=1,) class TelephonySynthesizeSpeech(proto.Message): r"""Synthesizes speech and plays back the synthesized audio to the @@ -774,13 +716,11 @@ class TelephonySynthesizeSpeech(proto.Message): `SSML `__. """ - text = proto.Field(proto.STRING, number=1, oneof="source") - - ssml = proto.Field(proto.STRING, number=2, oneof="source") + text = proto.Field(proto.STRING, number=1, oneof="source",) + ssml = proto.Field(proto.STRING, number=2, oneof="source",) class TelephonyTransferCall(proto.Message): r"""Transfers the call in Telephony Gateway. - Attributes: phone_number (str): Required. The phone number to transfer the call to in `E.164 @@ -790,11 +730,10 @@ class TelephonyTransferCall(proto.Message): (+1xxxyyyzzzz). """ - phone_number = proto.Field(proto.STRING, number=1) + phone_number = proto.Field(proto.STRING, number=1,) class RbmText(proto.Message): r"""Rich Business Messaging (RBM) text response with suggestions. - Attributes: text (str): Required. Text sent and displayed to the @@ -804,8 +743,7 @@ class RbmText(proto.Message): the user. """ - text = proto.Field(proto.STRING, number=1) - + text = proto.Field(proto.STRING, number=1,) rbm_suggestion = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.RbmSuggestion", ) @@ -840,7 +778,6 @@ class CardWidth(proto.Enum): card_width = proto.Field( proto.ENUM, number=1, enum="Intent.Message.RbmCarouselCard.CardWidth", ) - card_contents = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.RbmCardContent", ) @@ -885,20 +822,17 @@ class ThumbnailImageAlignment(proto.Enum): number=1, enum="Intent.Message.RbmStandaloneCard.CardOrientation", ) - thumbnail_image_alignment = proto.Field( proto.ENUM, number=2, enum="Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment", ) - card_content = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.RbmCardContent", ) class RbmCardContent(proto.Message): r"""Rich Business Messaging (RBM) Card content - Attributes: title (str): Optional. Title of the card (at most 200 @@ -970,26 +904,21 @@ class Height(proto.Enum): MEDIUM = 2 TALL = 3 - file_uri = proto.Field(proto.STRING, number=1) - - thumbnail_uri = proto.Field(proto.STRING, number=2) - + file_uri = proto.Field(proto.STRING, number=1,) + thumbnail_uri = proto.Field(proto.STRING, number=2,) height = proto.Field( proto.ENUM, number=3, enum="Intent.Message.RbmCardContent.RbmMedia.Height", ) - title = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) media = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.RbmCardContent.RbmMedia", ) - suggestions = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.RbmSuggestion", ) @@ -1014,7 +943,6 @@ class RbmSuggestion(proto.Message): oneof="suggestion", message="Intent.Message.RbmSuggestedReply", ) - action = proto.Field( proto.MESSAGE, number=2, @@ -1037,9 +965,8 @@ class RbmSuggestedReply(proto.Message): logic. """ - text = proto.Field(proto.STRING, number=1) - - postback_data = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + postback_data = proto.Field(proto.STRING, number=2,) class RbmSuggestedAction(proto.Message): r"""Rich Business Messaging (RBM) suggested client-side action @@ -1077,7 +1004,7 @@ class RbmSuggestedActionDial(proto.Message): example of a correctly formatted phone number: +15556767888. """ - phone_number = proto.Field(proto.STRING, number=1) + phone_number = proto.Field(proto.STRING, number=1,) class RbmSuggestedActionOpenUri(proto.Message): r"""Opens the user's default web browser app to the specified uri @@ -1091,31 +1018,27 @@ class RbmSuggestedActionOpenUri(proto.Message): Required. The uri to open on the user device """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class RbmSuggestedActionShareLocation(proto.Message): r"""Opens the device's location chooser so the user can pick a location to send back to the agent. - """ - - text = proto.Field(proto.STRING, number=1) - - postback_data = proto.Field(proto.STRING, number=2) + """ + text = proto.Field(proto.STRING, number=1,) + postback_data = proto.Field(proto.STRING, number=2,) dial = proto.Field( proto.MESSAGE, number=3, oneof="action", message="Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial", ) - open_url = proto.Field( proto.MESSAGE, number=4, oneof="action", message="Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri", ) - share_location = proto.Field( proto.MESSAGE, number=5, @@ -1125,7 +1048,6 @@ class RbmSuggestedActionShareLocation(proto.Message): class MediaContent(proto.Message): r"""The media content card for Actions on Google. - Attributes: media_type (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaType): Optional. What type of media is the content @@ -1141,7 +1063,6 @@ class ResponseMediaType(proto.Enum): class ResponseMediaObject(proto.Message): r"""Response media object for media content card. - Attributes: name (str): Required. Name of media card. @@ -1157,32 +1078,27 @@ class ResponseMediaObject(proto.Message): Required. Url where the media is stored. """ - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) large_image = proto.Field( proto.MESSAGE, number=3, oneof="image", message="Intent.Message.Image", ) - icon = proto.Field( proto.MESSAGE, number=4, oneof="image", message="Intent.Message.Image", ) - - content_url = proto.Field(proto.STRING, number=5) + content_url = proto.Field(proto.STRING, number=5,) media_type = proto.Field( proto.ENUM, number=1, enum="Intent.Message.MediaContent.ResponseMediaType", ) - media_objects = proto.RepeatedField( proto.MESSAGE, number=2, @@ -1217,7 +1133,6 @@ class ImageDisplayOptions(proto.Enum): class BrowseCarouselCardItem(proto.Message): r"""Browsing carousel tile - Attributes: open_uri_action (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): Required. Action to present to the user. @@ -1237,7 +1152,6 @@ class BrowseCarouselCardItem(proto.Message): class OpenUrlAction(proto.Message): r"""Actions on Google action to open a given url. - Attributes: url (str): Required. URL @@ -1253,8 +1167,7 @@ class UrlTypeHint(proto.Enum): AMP_ACTION = 1 AMP_CONTENT = 2 - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) url_type_hint = proto.Field( proto.ENUM, number=3, @@ -1266,23 +1179,18 @@ class UrlTypeHint(proto.Enum): number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - - footer = proto.Field(proto.STRING, number=5) + footer = proto.Field(proto.STRING, number=5,) items = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem", ) - image_display_options = proto.Field( proto.ENUM, number=2, @@ -1291,7 +1199,6 @@ class UrlTypeHint(proto.Enum): class TableCard(proto.Message): r"""Table card for Actions on Google. - Attributes: title (str): Required. Title of the card. @@ -1309,22 +1216,17 @@ class TableCard(proto.Message): Optional. List of buttons for the card. """ - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) image = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.Image", ) - column_properties = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.ColumnProperties", ) - rows = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.TableCardRow", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=6, message="Intent.Message.BasicCard.Button", ) @@ -1348,8 +1250,7 @@ class HorizontalAlignment(proto.Enum): CENTER = 2 TRAILING = 3 - header = proto.Field(proto.STRING, number=1) - + header = proto.Field(proto.STRING, number=1,) horizontal_alignment = proto.Field( proto.ENUM, number=2, @@ -1372,8 +1273,7 @@ class TableCardRow(proto.Message): cells = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.TableCardCell", ) - - divider_after = proto.Field(proto.BOOL, number=2) + divider_after = proto.Field(proto.BOOL, number=2,) class TableCardCell(proto.Message): r"""Cell of @@ -1384,138 +1284,117 @@ class TableCardCell(proto.Message): Required. Text in this cell. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) text = proto.Field( proto.MESSAGE, number=1, oneof="message", message="Intent.Message.Text", ) - image = proto.Field( proto.MESSAGE, number=2, oneof="message", message="Intent.Message.Image", ) - quick_replies = proto.Field( proto.MESSAGE, number=3, oneof="message", message="Intent.Message.QuickReplies", ) - card = proto.Field( proto.MESSAGE, number=4, oneof="message", message="Intent.Message.Card", ) - payload = proto.Field( - proto.MESSAGE, number=5, oneof="message", message=struct.Struct, + proto.MESSAGE, number=5, oneof="message", message=struct_pb2.Struct, ) - simple_responses = proto.Field( proto.MESSAGE, number=7, oneof="message", message="Intent.Message.SimpleResponses", ) - basic_card = proto.Field( proto.MESSAGE, number=8, oneof="message", message="Intent.Message.BasicCard", ) - suggestions = proto.Field( proto.MESSAGE, number=9, oneof="message", message="Intent.Message.Suggestions", ) - link_out_suggestion = proto.Field( proto.MESSAGE, number=10, oneof="message", message="Intent.Message.LinkOutSuggestion", ) - list_select = proto.Field( proto.MESSAGE, number=11, oneof="message", message="Intent.Message.ListSelect", ) - carousel_select = proto.Field( proto.MESSAGE, number=12, oneof="message", message="Intent.Message.CarouselSelect", ) - telephony_play_audio = proto.Field( proto.MESSAGE, number=13, oneof="message", message="Intent.Message.TelephonyPlayAudio", ) - telephony_synthesize_speech = proto.Field( proto.MESSAGE, number=14, oneof="message", message="Intent.Message.TelephonySynthesizeSpeech", ) - telephony_transfer_call = proto.Field( proto.MESSAGE, number=15, oneof="message", message="Intent.Message.TelephonyTransferCall", ) - rbm_text = proto.Field( proto.MESSAGE, number=18, oneof="message", message="Intent.Message.RbmText", ) - rbm_standalone_rich_card = proto.Field( proto.MESSAGE, number=19, oneof="message", message="Intent.Message.RbmStandaloneCard", ) - rbm_carousel_rich_card = proto.Field( proto.MESSAGE, number=20, oneof="message", message="Intent.Message.RbmCarouselCard", ) - browse_carousel_card = proto.Field( proto.MESSAGE, number=22, oneof="message", message="Intent.Message.BrowseCarouselCard", ) - table_card = proto.Field( proto.MESSAGE, number=23, oneof="message", message="Intent.Message.TableCard", ) - media_content = proto.Field( proto.MESSAGE, number=24, oneof="message", message="Intent.Message.MediaContent", ) - platform = proto.Field(proto.ENUM, number=6, enum="Intent.Message.Platform",) class FollowupIntentInfo(proto.Message): r"""Represents a single followup intent in the chain. - Attributes: followup_intent_name (str): The unique identifier of the followup intent. Format: @@ -1525,56 +1404,35 @@ class FollowupIntentInfo(proto.Message): Format: ``projects//agent/intents/``. """ - followup_intent_name = proto.Field(proto.STRING, number=1) - - parent_followup_intent_name = proto.Field(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + followup_intent_name = proto.Field(proto.STRING, number=1,) + parent_followup_intent_name = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) webhook_state = proto.Field(proto.ENUM, number=6, enum=WebhookState,) - - priority = proto.Field(proto.INT32, number=3) - - is_fallback = proto.Field(proto.BOOL, number=4) - - ml_enabled = proto.Field(proto.BOOL, number=5) - - ml_disabled = proto.Field(proto.BOOL, number=19) - - live_agent_handoff = proto.Field(proto.BOOL, number=20) - - end_interaction = proto.Field(proto.BOOL, number=21) - - input_context_names = proto.RepeatedField(proto.STRING, number=7) - - events = proto.RepeatedField(proto.STRING, number=8) - + priority = proto.Field(proto.INT32, number=3,) + is_fallback = proto.Field(proto.BOOL, number=4,) + ml_enabled = proto.Field(proto.BOOL, number=5,) + ml_disabled = proto.Field(proto.BOOL, number=19,) + live_agent_handoff = proto.Field(proto.BOOL, number=20,) + end_interaction = proto.Field(proto.BOOL, number=21,) + input_context_names = proto.RepeatedField(proto.STRING, number=7,) + events = proto.RepeatedField(proto.STRING, number=8,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=9, message=TrainingPhrase, ) - - action = proto.Field(proto.STRING, number=10) - + action = proto.Field(proto.STRING, number=10,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message=context.Context, ) - - reset_contexts = proto.Field(proto.BOOL, number=12) - + reset_contexts = proto.Field(proto.BOOL, number=12,) parameters = proto.RepeatedField(proto.MESSAGE, number=13, message=Parameter,) - messages = proto.RepeatedField(proto.MESSAGE, number=14, message=Message,) - default_response_platforms = proto.RepeatedField( proto.ENUM, number=15, enum=Message.Platform, ) - - root_followup_intent_name = proto.Field(proto.STRING, number=16) - - parent_followup_intent_name = proto.Field(proto.STRING, number=17) - + root_followup_intent_name = proto.Field(proto.STRING, number=16,) + parent_followup_intent_name = proto.Field(proto.STRING, number=17,) followup_intent_info = proto.RepeatedField( proto.MESSAGE, number=18, message=FollowupIntentInfo, ) @@ -1606,15 +1464,11 @@ class ListIntentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) class ListIntentsResponse(proto.Message): @@ -1636,8 +1490,7 @@ def raw_page(self): return self intents = proto.RepeatedField(proto.MESSAGE, number=1, message="Intent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetIntentRequest(proto.Message): @@ -1661,10 +1514,8 @@ class GetIntentRequest(proto.Message): returned intent. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) @@ -1692,12 +1543,9 @@ class CreateIntentRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intent = proto.Field(proto.MESSAGE, number=2, message="Intent",) - - language_code = proto.Field(proto.STRING, number=3) - + language_code = proto.Field(proto.STRING, number=3,) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1723,11 +1571,10 @@ class UpdateIntentRequest(proto.Message): """ intent = proto.Field(proto.MESSAGE, number=1, message="Intent",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1747,7 +1594,7 @@ class DeleteIntentRequest(proto.Message): - ``projects//locations//agent/intents/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateIntentsRequest(proto.Message): @@ -1784,18 +1631,15 @@ class BatchUpdateIntentsRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - - intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch") - + parent = proto.Field(proto.STRING, number=1,) + intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch",) intent_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="intent_batch", message="IntentBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=6, enum="IntentView",) @@ -1827,14 +1671,12 @@ class BatchDeleteIntentsRequest(proto.Message): ``name`` must be filled in. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intents = proto.RepeatedField(proto.MESSAGE, number=2, message="Intent",) class IntentBatch(proto.Message): r"""This message is a wrapper around a collection of intents. - Attributes: intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): A collection of intents. diff --git a/google/cloud/dialogflow_v2beta1/types/knowledge_base.py b/google/cloud/dialogflow_v2beta1/types/knowledge_base.py index aac1458c9..bc167796b 100644 --- a/google/cloud/dialogflow_v2beta1/types/knowledge_base.py +++ b/google/cloud/dialogflow_v2beta1/types/knowledge_base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -64,11 +61,9 @@ class KnowledgeBase(proto.Message): populated, the default language en-us applies. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=4,) class ListKnowledgeBasesRequest(proto.Message): @@ -116,13 +111,10 @@ class ListKnowledgeBasesRequest(proto.Message): Filtering `__. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListKnowledgeBasesResponse(proto.Message): @@ -145,8 +137,7 @@ def raw_page(self): knowledge_bases = proto.RepeatedField( proto.MESSAGE, number=1, message="KnowledgeBase", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetKnowledgeBaseRequest(proto.Message): @@ -159,7 +150,7 @@ class GetKnowledgeBaseRequest(proto.Message): ``projects//locations//knowledgeBases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateKnowledgeBaseRequest(proto.Message): @@ -174,8 +165,7 @@ class CreateKnowledgeBaseRequest(proto.Message): Required. The knowledge base to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) knowledge_base = proto.Field(proto.MESSAGE, number=2, message="KnowledgeBase",) @@ -193,9 +183,8 @@ class DeleteKnowledgeBaseRequest(proto.Message): base are also deleted. """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class UpdateKnowledgeBaseRequest(proto.Message): @@ -212,8 +201,9 @@ class UpdateKnowledgeBaseRequest(proto.Message): """ knowledge_base = proto.Field(proto.MESSAGE, number=1, message="KnowledgeBase",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/participant.py b/google/cloud/dialogflow_v2beta1/types/participant.py index 1cc49a74a..b38c7e8a9 100644 --- a/google/cloud/dialogflow_v2beta1/types/participant.py +++ b/google/cloud/dialogflow_v2beta1/types/participant.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -123,16 +120,13 @@ class Role(proto.Enum): AUTOMATED_AGENT = 2 END_USER = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) role = proto.Field(proto.ENUM, number=2, enum=Role,) - - obfuscated_external_user_id = proto.Field(proto.STRING, number=7) + obfuscated_external_user_id = proto.Field(proto.STRING, number=7,) class Message(proto.Message): r"""Represents a message posted into a conversation. - Attributes: name (str): Optional. The unique identifier of the message. Format: @@ -160,24 +154,16 @@ class Message(proto.Message): for the message. """ - name = proto.Field(proto.STRING, number=1) - - content = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - participant = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + content = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + participant = proto.Field(proto.STRING, number=4,) participant_role = proto.Field(proto.ENUM, number=5, enum="Participant.Role",) - - create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - - send_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) + send_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) message_annotation = proto.Field( proto.MESSAGE, number=7, message="MessageAnnotation", ) - sentiment_analysis = proto.Field( proto.MESSAGE, number=8, message=session.SentimentAnalysisResult, ) @@ -196,8 +182,7 @@ class CreateParticipantRequest(proto.Message): Required. The participant to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) participant = proto.Field(proto.MESSAGE, number=2, message="Participant",) @@ -211,7 +196,7 @@ class GetParticipantRequest(proto.Message): ``projects//locations//conversations//participants/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListParticipantsRequest(proto.Message): @@ -232,11 +217,9 @@ class ListParticipantsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListParticipantsResponse(proto.Message): @@ -257,8 +240,7 @@ def raw_page(self): return self participants = proto.RepeatedField(proto.MESSAGE, number=1, message="Participant",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateParticipantRequest(proto.Message): @@ -274,8 +256,9 @@ class UpdateParticipantRequest(proto.Message): """ participant = proto.Field(proto.MESSAGE, number=1, message="Participant",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class OutputAudio(proto.Message): @@ -293,13 +276,11 @@ class OutputAudio(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class AutomatedAgentReply(proto.Message): r"""Represents a response from an automated agent. - Attributes: detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): Response of the Dialogflow @@ -324,16 +305,14 @@ class AutomatedAgentReply(proto.Message): detect_intent_response = proto.Field( proto.MESSAGE, number=1, oneof="response", message=session.DetectIntentResponse, ) - response_messages = proto.RepeatedField( proto.MESSAGE, number=3, message="ResponseMessage", ) - - intent = proto.Field(proto.STRING, number=4, oneof="match") - - event = proto.Field(proto.STRING, number=5, oneof="match") - - cx_session_parameters = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + intent = proto.Field(proto.STRING, number=4, oneof="match",) + event = proto.Field(proto.STRING, number=5, oneof="match",) + cx_session_parameters = proto.Field( + proto.MESSAGE, number=6, message=struct_pb2.Struct, + ) class SuggestionFeature(proto.Message): @@ -404,29 +383,23 @@ class AnalyzeContentRequest(proto.Message): only idempotent if a ``request_id`` is provided. """ - participant = proto.Field(proto.STRING, number=1) - + participant = proto.Field(proto.STRING, number=1,) text_input = proto.Field( proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) - reply_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) - query_params = proto.Field( proto.MESSAGE, number=9, message=session.QueryParameters, ) - message_send_time = proto.Field( - proto.MESSAGE, number=10, message=timestamp.Timestamp, + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, ) - - request_id = proto.Field(proto.STRING, number=11) + request_id = proto.Field(proto.STRING, number=11,) class DtmfParameters(proto.Message): @@ -439,7 +412,7 @@ class DtmfParameters(proto.Message): in the next request. """ - accepts_dtmf_input = proto.Field(proto.BOOL, number=1) + accepts_dtmf_input = proto.Field(proto.BOOL, number=1,) class AnalyzeContentResponse(proto.Message): @@ -489,24 +462,18 @@ class AnalyzeContentResponse(proto.Message): Indicates the parameters of DTMF. """ - reply_text = proto.Field(proto.STRING, number=1) - + reply_text = proto.Field(proto.STRING, number=1,) reply_audio = proto.Field(proto.MESSAGE, number=2, message="OutputAudio",) - automated_agent_reply = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentReply", ) - message = proto.Field(proto.MESSAGE, number=5, message="Message",) - human_agent_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=6, message="SuggestionResult", ) - end_user_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=7, message="SuggestionResult", ) - dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) @@ -540,16 +507,13 @@ class AnnotatedMessagePart(proto.Message): """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct.Value,) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Value,) class MessageAnnotation(proto.Message): r"""Represents the result of annotation for the message. - Attributes: parts (Sequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): Optional. The collection of annotated message parts ordered @@ -564,13 +528,11 @@ class MessageAnnotation(proto.Message): parts = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotatedMessagePart", ) - - contain_entities = proto.Field(proto.BOOL, number=2) + contain_entities = proto.Field(proto.BOOL, number=2,) class ArticleAnswer(proto.Message): r"""Represents article answer. - Attributes: title (str): The article title. @@ -587,20 +549,15 @@ class ArticleAnswer(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents answer from "frequently asked questions". - Attributes: answer (str): The piece of text from the ``source`` knowledge base @@ -625,22 +582,16 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class SmartReplyAnswer(proto.Message): r"""Represents a smart reply answer. - Attributes: reply (str): The content of the reply. @@ -656,11 +607,9 @@ class SmartReplyAnswer(proto.Message): ID>/answerRecords/". """ - reply = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - answer_record = proto.Field(proto.STRING, number=3) + reply = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + answer_record = proto.Field(proto.STRING, number=3,) class SuggestionResult(proto.Message): @@ -685,23 +634,20 @@ class SuggestionResult(proto.Message): """ error = proto.Field( - proto.MESSAGE, number=1, oneof="suggestion_response", message=status.Status, + proto.MESSAGE, number=1, oneof="suggestion_response", message=status_pb2.Status, ) - suggest_articles_response = proto.Field( proto.MESSAGE, number=2, oneof="suggestion_response", message="SuggestArticlesResponse", ) - suggest_faq_answers_response = proto.Field( proto.MESSAGE, number=3, oneof="suggestion_response", message="SuggestFaqAnswersResponse", ) - suggest_smart_replies_response = proto.Field( proto.MESSAGE, number=4, @@ -733,11 +679,9 @@ class SuggestArticlesRequest(proto.Message): 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestArticlesResponse(proto.Message): @@ -766,10 +710,8 @@ class SuggestArticlesResponse(proto.Message): article_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="ArticleAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersRequest(proto.Message): @@ -794,11 +736,9 @@ class SuggestFaqAnswersRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersResponse(proto.Message): @@ -825,10 +765,8 @@ class SuggestFaqAnswersResponse(proto.Message): """ faq_answers = proto.RepeatedField(proto.MESSAGE, number=1, message="FaqAnswer",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestSmartRepliesRequest(proto.Message): @@ -859,15 +797,12 @@ class SuggestSmartRepliesRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) current_text_input = proto.Field( proto.MESSAGE, number=4, message=session.TextInput, ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestSmartRepliesResponse(proto.Message): @@ -899,15 +834,12 @@ class SuggestSmartRepliesResponse(proto.Message): smart_reply_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="SmartReplyAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class Suggestion(proto.Message): r"""Represents a suggestion for a human agent. - Attributes: name (str): Output only. The name of this suggestion. Format: @@ -931,7 +863,6 @@ class Suggestion(proto.Message): class Article(proto.Message): r"""Represents suggested article. - Attributes: title (str): Output only. The article title. @@ -950,15 +881,11 @@ class Article(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents suggested answer from "frequently asked @@ -990,27 +917,18 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) - - name = proto.Field(proto.STRING, number=1) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) + name = proto.Field(proto.STRING, number=1,) articles = proto.RepeatedField(proto.MESSAGE, number=2, message=Article,) - faq_answers = proto.RepeatedField(proto.MESSAGE, number=4, message=FaqAnswer,) - - create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - latest_message = proto.Field(proto.STRING, number=7) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + latest_message = proto.Field(proto.STRING, number=7,) class ListSuggestionsRequest(proto.Message): @@ -1035,19 +953,16 @@ class ListSuggestionsRequest(proto.Message): are supported. ``create_time`` only support milliseconds accuracy. E.g., ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > 2017-01-15T01:30:15.01Z`` + ``create_time > "2017-01-15T01:30:15.01Z"`` For more information about filtering, see `API Filtering `__. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListSuggestionsResponse(proto.Message): @@ -1071,8 +986,7 @@ def raw_page(self): return self suggestions = proto.RepeatedField(proto.MESSAGE, number=1, message="Suggestion",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CompileSuggestionRequest(proto.Message): @@ -1097,11 +1011,9 @@ class CompileSuggestionRequest(proto.Message): suggestion. If zero or less than zero, 20 is used. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class CompileSuggestionResponse(proto.Message): @@ -1127,15 +1039,12 @@ class CompileSuggestionResponse(proto.Message): """ suggestion = proto.Field(proto.MESSAGE, number=1, message="Suggestion",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class ResponseMessage(proto.Message): r"""Response messages from an automated agent. - Attributes: text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): Returns a text response. @@ -1151,13 +1060,12 @@ class ResponseMessage(proto.Message): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): A collection of text responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class LiveAgentHandoff(proto.Message): r"""Indicates that the conversation should be handed off to a human @@ -1180,23 +1088,20 @@ class LiveAgentHandoff(proto.Message): Dialogflow doesn't impose any structure on this. """ - metadata = proto.Field(proto.MESSAGE, number=1, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=1, message=struct_pb2.Struct,) class EndInteraction(proto.Message): r"""Indicates that interaction with the Dialogflow agent has ended. - """ + """ text = proto.Field(proto.MESSAGE, number=1, oneof="message", message=Text,) - payload = proto.Field( - proto.MESSAGE, number=2, oneof="message", message=struct.Struct, + proto.MESSAGE, number=2, oneof="message", message=struct_pb2.Struct, ) - live_agent_handoff = proto.Field( proto.MESSAGE, number=3, oneof="message", message=LiveAgentHandoff, ) - end_interaction = proto.Field( proto.MESSAGE, number=4, oneof="message", message=EndInteraction, ) diff --git a/google/cloud/dialogflow_v2beta1/types/session.py b/google/cloud/dialogflow_v2beta1/types/session.py index 83f336c1d..6423b5774 100644 --- a/google/cloud/dialogflow_v2beta1/types/session.py +++ b/google/cloud/dialogflow_v2beta1/types/session.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config as gcd_audio_config from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -53,7 +50,6 @@ class DetectIntentRequest(proto.Message): r"""The request to detect user's intent. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -113,26 +109,20 @@ class DetectIntentRequest(proto.Message): minute of speech audio data. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=5) + input_audio = proto.Field(proto.BYTES, number=5,) class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): The unique identifier of the response. It can @@ -171,18 +161,13 @@ class DetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=5, message="QueryResult", ) - - webhook_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=4) - + webhook_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -190,7 +175,6 @@ class DetectIntentResponse(proto.Message): class QueryParameters(proto.Message): r"""Represents the parameters of the conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -251,29 +235,20 @@ class QueryParameters(proto.Message): None-Match", "X-Forwarded-For", etc. """ - time_zone = proto.Field(proto.STRING, number=1) - - geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) - + time_zone = proto.Field(proto.STRING, number=1,) + geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) contexts = proto.RepeatedField(proto.MESSAGE, number=3, message=context.Context,) - - reset_contexts = proto.Field(proto.BOOL, number=4) - + reset_contexts = proto.Field(proto.BOOL, number=4,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=5, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - - knowledge_base_names = proto.RepeatedField(proto.STRING, number=12) - + payload = proto.Field(proto.MESSAGE, number=6, message=struct_pb2.Struct,) + knowledge_base_names = proto.RepeatedField(proto.STRING, number=12,) sentiment_analysis_request_config = proto.Field( proto.MESSAGE, number=10, message="SentimentAnalysisRequestConfig", ) - sub_agents = proto.RepeatedField(proto.MESSAGE, number=13, message=agent.SubAgent,) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14,) class QueryInput(proto.Message): @@ -304,11 +279,8 @@ class QueryInput(proto.Message): oneof="input", message=gcd_audio_config.InputAudioConfig, ) - text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - event = proto.Field(proto.MESSAGE, number=3, oneof="input", message="EventInput",) - dtmf = proto.Field( proto.MESSAGE, number=4, @@ -436,42 +408,27 @@ class QueryResult(proto.Message): decreasing ``KnowledgeAnswers.match_confidence``. """ - query_text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=15) - - speech_recognition_confidence = proto.Field(proto.FLOAT, number=2) - - action = proto.Field(proto.STRING, number=3) - - parameters = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - all_required_params_present = proto.Field(proto.BOOL, number=5) - - fulfillment_text = proto.Field(proto.STRING, number=6) - + query_text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=15,) + speech_recognition_confidence = proto.Field(proto.FLOAT, number=2,) + action = proto.Field(proto.STRING, number=3,) + parameters = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + all_required_params_present = proto.Field(proto.BOOL, number=5,) + fulfillment_text = proto.Field(proto.STRING, number=6,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_intent.Intent.Message, ) - - webhook_source = proto.Field(proto.STRING, number=8) - - webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) - + webhook_source = proto.Field(proto.STRING, number=8,) + webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=10, message=context.Context, ) - intent = proto.Field(proto.MESSAGE, number=11, message=gcd_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=12) - - diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct.Struct,) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=12,) + diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) - knowledge_answers = proto.Field( proto.MESSAGE, number=18, message="KnowledgeAnswers", ) @@ -479,7 +436,6 @@ class QueryResult(proto.Message): class KnowledgeAnswers(proto.Message): r"""Represents the result of querying a Knowledge base. - Attributes: answers (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): A list of answers from Knowledge Connector. @@ -487,7 +443,6 @@ class KnowledgeAnswers(proto.Message): class Answer(proto.Message): r"""An answer from Knowledge Connector. - Attributes: source (str): Indicates which Knowledge Document this answer was extracted @@ -528,17 +483,13 @@ class MatchConfidenceLevel(proto.Enum): MEDIUM = 2 HIGH = 3 - source = proto.Field(proto.STRING, number=1) - - faq_question = proto.Field(proto.STRING, number=2) - - answer = proto.Field(proto.STRING, number=3) - + source = proto.Field(proto.STRING, number=1,) + faq_question = proto.Field(proto.STRING, number=2,) + answer = proto.Field(proto.STRING, number=3,) match_confidence_level = proto.Field( proto.ENUM, number=4, enum="KnowledgeAnswers.Answer.MatchConfidenceLevel", ) - - match_confidence = proto.Field(proto.FLOAT, number=5) + match_confidence = proto.Field(proto.FLOAT, number=5,) answers = proto.RepeatedField(proto.MESSAGE, number=1, message=Answer,) @@ -653,23 +604,17 @@ class StreamingDetectIntentRequest(proto.Message): exceed 1 minute. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - - single_utterance = proto.Field(proto.BOOL, number=4) - + single_utterance = proto.Field(proto.BOOL, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=6) + input_audio = proto.Field(proto.BYTES, number=6,) class StreamingDetectIntentResponse(proto.Message): @@ -732,22 +677,16 @@ class StreamingDetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) recognition_result = proto.Field( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - query_result = proto.Field(proto.MESSAGE, number=3, message="QueryResult",) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=7, message="QueryResult", ) - - webhook_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=5) - + webhook_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=5,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -841,21 +780,16 @@ class MessageType(proto.Enum): END_OF_SINGLE_UTTERANCE = 2 message_type = proto.Field(proto.ENUM, number=1, enum=MessageType,) - - transcript = proto.Field(proto.STRING, number=2) - - is_final = proto.Field(proto.BOOL, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - stability = proto.Field(proto.FLOAT, number=6) - + transcript = proto.Field(proto.STRING, number=2,) + is_final = proto.Field(proto.BOOL, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + stability = proto.Field(proto.FLOAT, number=6,) speech_word_info = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_audio_config.SpeechWordInfo, ) - - speech_end_offset = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) - + speech_end_offset = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration, + ) dtmf_digits = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.TelephonyDtmfEvents, ) @@ -863,7 +797,6 @@ class MessageType(proto.Enum): class TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -878,9 +811,8 @@ class TextInput(proto.Message): specify the same language. """ - text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class EventInput(proto.Message): @@ -922,16 +854,13 @@ class EventInput(proto.Message): specify the same language. """ - name = proto.Field(proto.STRING, number=1) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - language_code = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + language_code = proto.Field(proto.STRING, number=3,) class SentimentAnalysisRequestConfig(proto.Message): r"""Configures the types of sentiment analysis to perform. - Attributes: analyze_query_text_sentiment (bool): Instructs the service to perform sentiment analysis on @@ -939,7 +868,7 @@ class SentimentAnalysisRequestConfig(proto.Message): performed on ``query_text``. """ - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1,) class SentimentAnalysisResult(proto.Message): @@ -980,9 +909,8 @@ class Sentiment(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/session_entity_type.py b/google/cloud/dialogflow_v2beta1/types/session_entity_type.py index 2cf83c8da..a3d4a2838 100644 --- a/google/cloud/dialogflow_v2beta1/types/session_entity_type.py +++ b/google/cloud/dialogflow_v2beta1/types/session_entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import entity_type -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -79,10 +76,8 @@ class EntityOverrideMode(proto.Enum): ENTITY_OVERRIDE_MODE_OVERRIDE = 1 ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) entity_override_mode = proto.Field(proto.ENUM, number=2, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=3, message=entity_type.EntityType.Entity, ) @@ -115,11 +110,9 @@ class ListSessionEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSessionEntityTypesResponse(proto.Message): @@ -144,8 +137,7 @@ def raw_page(self): session_entity_types = proto.RepeatedField( proto.MESSAGE, number=1, message="SessionEntityType", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetSessionEntityTypeRequest(proto.Message): @@ -168,7 +160,7 @@ class GetSessionEntityTypeRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -193,8 +185,7 @@ class CreateSessionEntityTypeRequest(proto.Message): Required. The session entity type to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) session_entity_type = proto.Field( proto.MESSAGE, number=2, message="SessionEntityType", ) @@ -215,8 +206,9 @@ class UpdateSessionEntityTypeRequest(proto.Message): session_entity_type = proto.Field( proto.MESSAGE, number=1, message="SessionEntityType", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteSessionEntityTypeRequest(proto.Message): @@ -239,7 +231,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/validation_result.py b/google/cloud/dialogflow_v2beta1/types/validation_result.py index 1371ba1ca..4bd7018e5 100644 --- a/google/cloud/dialogflow_v2beta1/types/validation_result.py +++ b/google/cloud/dialogflow_v2beta1/types/validation_result.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class ValidationError(proto.Message): r"""Represents a single validation error. - Attributes: severity (google.cloud.dialogflow_v2beta1.types.ValidationError.Severity): The severity of the error. @@ -63,15 +60,12 @@ class Severity(proto.Enum): CRITICAL = 4 severity = proto.Field(proto.ENUM, number=1, enum=Severity,) - - entries = proto.RepeatedField(proto.STRING, number=3) - - error_message = proto.Field(proto.STRING, number=4) + entries = proto.RepeatedField(proto.STRING, number=3,) + error_message = proto.Field(proto.STRING, number=4,) class ValidationResult(proto.Message): r"""Represents the output of agent validation. - Attributes: validation_errors (Sequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): Contains all validation errors. diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py b/google/cloud/dialogflow_v2beta1/types/version.py similarity index 79% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py rename to google/cloud/dialogflow_v2beta1/types/version.py index c1795217f..623c33e1e 100644 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py +++ b/google/cloud/dialogflow_v2beta1/types/version.py @@ -20,15 +20,15 @@ __protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', + package="google.cloud.dialogflow.v2beta1", manifest={ - 'Version', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'GetVersionRequest', - 'CreateVersionRequest', - 'UpdateVersionRequest', - 'DeleteVersionRequest', + "Version", + "ListVersionsRequest", + "ListVersionsResponse", + "GetVersionRequest", + "CreateVersionRequest", + "UpdateVersionRequest", + "DeleteVersionRequest", }, ) @@ -77,6 +77,7 @@ class Version(proto.Message): field is read-only and cannot be set by create and update methods. """ + class VersionStatus(proto.Enum): r"""The status of a version.""" VERSION_STATUS_UNSPECIFIED = 0 @@ -84,28 +85,11 @@ class VersionStatus(proto.Enum): READY = 2 FAILED = 3 - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - version_number = proto.Field( - proto.INT32, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - status = proto.Field( - proto.ENUM, - number=6, - enum=VersionStatus, - ) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + version_number = proto.Field(proto.INT32, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.ENUM, number=6, enum=VersionStatus,) class ListVersionsRequest(proto.Message): @@ -128,18 +112,9 @@ class ListVersionsRequest(proto.Message): list request. """ - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListVersionsResponse(proto.Message): @@ -161,15 +136,8 @@ class ListVersionsResponse(proto.Message): def raw_page(self): return self - versions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Version', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) + versions = proto.RepeatedField(proto.MESSAGE, number=1, message="Version",) + next_page_token = proto.Field(proto.STRING, number=2,) class GetVersionRequest(proto.Message): @@ -184,10 +152,7 @@ class GetVersionRequest(proto.Message): - ``projects//locations//agent/versions/`` """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) class CreateVersionRequest(proto.Message): @@ -205,15 +170,8 @@ class CreateVersionRequest(proto.Message): Required. The version to create. """ - parent = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message='Version', - ) + parent = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.MESSAGE, number=2, message="Version",) class UpdateVersionRequest(proto.Message): @@ -231,15 +189,9 @@ class UpdateVersionRequest(proto.Message): get updated. """ - version = proto.Field( - proto.MESSAGE, - number=1, - message='Version', - ) + version = proto.Field(proto.MESSAGE, number=1, message="Version",) update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) @@ -256,10 +208,7 @@ class DeleteVersionRequest(proto.Message): - ``projects//locations//agent/versions/`` """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/webhook.py b/google/cloud/dialogflow_v2beta1/types/webhook.py index 05ea8848d..cc7911ca4 100644 --- a/google/cloud/dialogflow_v2beta1/types/webhook.py +++ b/google/cloud/dialogflow_v2beta1/types/webhook.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import session as gcd_session from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -33,7 +30,6 @@ class WebhookRequest(proto.Message): r"""The request message for a webhook call. - Attributes: session (str): The unique identifier of detectIntent request session. Can @@ -59,18 +55,14 @@ class WebhookRequest(proto.Message): passed to ``[Streaming]DetectIntent`` call. """ - session = proto.Field(proto.STRING, number=4) - - response_id = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=4,) + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field( proto.MESSAGE, number=2, message=gcd_session.QueryResult, ) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_session.QueryResult, ) - original_detect_intent_request = proto.Field( proto.MESSAGE, number=3, message="OriginalDetectIntentRequest", ) @@ -157,28 +149,20 @@ class WebhookResponse(proto.Message): management methods. """ - fulfillment_text = proto.Field(proto.STRING, number=1) - + fulfillment_text = proto.Field(proto.STRING, number=1,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=intent.Intent.Message, ) - - source = proto.Field(proto.STRING, number=3) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + source = proto.Field(proto.STRING, number=3,) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=5, message=context.Context, ) - followup_event_input = proto.Field( proto.MESSAGE, number=6, message=gcd_session.EventInput, ) - - live_agent_handoff = proto.Field(proto.BOOL, number=7) - - end_interaction = proto.Field(proto.BOOL, number=8) - + live_agent_handoff = proto.Field(proto.BOOL, number=7,) + end_interaction = proto.Field(proto.BOOL, number=8,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=10, message=session_entity_type.SessionEntityType, ) @@ -218,11 +202,9 @@ class OriginalDetectIntentRequest(proto.Message): Essentials Edition agents. """ - source = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - payload = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + source = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + payload = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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 8b2599a7e..000000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-dialogflow" -copyright = u"2020, 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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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_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/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 8bdbdfe41..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/services.rst +++ /dev/null @@ -1,20 +0,0 @@ -Services for Google Cloud Dialogflow v2 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/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 205c4fadd..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Dialogflow v2 API -======================================== - -.. automodule:: google.cloud.dialogflow_v2.types - :members: - :undoc-members: - :show-inheritance: 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 641057fda..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py +++ /dev/null @@ -1,419 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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_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 VoiceSelectionParams -from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding -from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding -from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant -from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender -from google.cloud.dialogflow_v2.types.context import Context -from google.cloud.dialogflow_v2.types.context import CreateContextRequest -from google.cloud.dialogflow_v2.types.context import DeleteAllContextsRequest -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_event import ConversationEvent -from google.cloud.dialogflow_v2.types.conversation_profile import AutomatedAgentConfig -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 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 GetDocumentRequest -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.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 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 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 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 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', - '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', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SuggestionFeature', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'GetDocumentRequest', - 'KnowledgeOperationMetadata', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'ReloadDocumentRequest', - 'UpdateDocumentRequest', - 'BatchCreateEntitiesRequest', - 'BatchDeleteEntitiesRequest', - 'BatchDeleteEntityTypesRequest', - 'BatchUpdateEntitiesRequest', - 'BatchUpdateEntityTypesRequest', - 'BatchUpdateEntityTypesResponse', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'EntityTypeBatch', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'EnvironmentHistory', - 'GetEnvironmentHistoryRequest', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'TextToSpeechSettings', - 'UpdateEnvironmentRequest', - 'Fulfillment', - 'GetFulfillmentRequest', - 'UpdateFulfillmentRequest', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AutomatedAgentReply', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestionResult', - '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/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 25fc98a76..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py +++ /dev/null @@ -1,420 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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 VoiceSelectionParams -from .types.audio_config import AudioEncoding -from .types.audio_config import OutputAudioEncoding -from .types.audio_config import SpeechModelVariant -from .types.audio_config import SsmlVoiceGender -from .types.context import Context -from .types.context import CreateContextRequest -from .types.context import DeleteAllContextsRequest -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_event import ConversationEvent -from .types.conversation_profile import AutomatedAgentConfig -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 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 GetDocumentRequest -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.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 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 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 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 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', - 'ConversationProfilesAsyncClient', - 'ConversationsAsyncClient', - 'DocumentsAsyncClient', - 'EntityTypesAsyncClient', - 'EnvironmentsAsyncClient', - 'FulfillmentsAsyncClient', - 'IntentsAsyncClient', - 'KnowledgeBasesAsyncClient', - 'ParticipantsAsyncClient', - 'SessionEntityTypesAsyncClient', - 'SessionsAsyncClient', - 'VersionsAsyncClient', -'Agent', -'AgentAssistantFeedback', -'AgentAssistantRecord', -'AgentsClient', -'AnalyzeContentRequest', -'AnalyzeContentResponse', -'AnnotatedMessagePart', -'AnswerFeedback', -'AnswerRecord', -'AnswerRecordsClient', -'ArticleAnswer', -'AudioEncoding', -'AutomatedAgentConfig', -'AutomatedAgentReply', -'BatchCreateEntitiesRequest', -'BatchDeleteEntitiesRequest', -'BatchDeleteEntityTypesRequest', -'BatchDeleteIntentsRequest', -'BatchUpdateEntitiesRequest', -'BatchUpdateEntityTypesRequest', -'BatchUpdateEntityTypesResponse', -'BatchUpdateIntentsRequest', -'BatchUpdateIntentsResponse', -'CompleteConversationRequest', -'Context', -'ContextsClient', -'Conversation', -'ConversationEvent', -'ConversationPhoneNumber', -'ConversationProfile', -'ConversationProfilesClient', -'ConversationsClient', -'CreateContextRequest', -'CreateConversationProfileRequest', -'CreateConversationRequest', -'CreateDocumentRequest', -'CreateEntityTypeRequest', -'CreateEnvironmentRequest', -'CreateIntentRequest', -'CreateKnowledgeBaseRequest', -'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', -'FaqAnswer', -'Fulfillment', -'FulfillmentsClient', -'GetAgentRequest', -'GetContextRequest', -'GetConversationProfileRequest', -'GetConversationRequest', -'GetDocumentRequest', -'GetEntityTypeRequest', -'GetEnvironmentHistoryRequest', -'GetEnvironmentRequest', -'GetFulfillmentRequest', -'GetIntentRequest', -'GetKnowledgeBaseRequest', -'GetParticipantRequest', -'GetSessionEntityTypeRequest', -'GetValidationResultRequest', -'GetVersionRequest', -'HumanAgentAssistantConfig', -'HumanAgentAssistantEvent', -'HumanAgentHandoffConfig', -'ImportAgentRequest', -'InputAudioConfig', -'Intent', -'IntentBatch', -'IntentView', -'IntentsClient', -'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', -'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', -'SpeechContext', -'SpeechModelVariant', -'SpeechToTextConfig', -'SpeechWordInfo', -'SsmlVoiceGender', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SuggestArticlesRequest', -'SuggestArticlesResponse', -'SuggestFaqAnswersRequest', -'SuggestFaqAnswersResponse', -'SuggestionFeature', -'SuggestionResult', -'SynthesizeSpeechConfig', -'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/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/agents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py deleted file mode 100644 index 057c8b80b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 f4b5b9026..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py +++ /dev/null @@ -1,922 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AgentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: agent.GetAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_agent.SetAgentRequest = None, - *, - agent: gcd_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.SetAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: agent.DeleteAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.SearchAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.SearchAgentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.TrainAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.TrainAgentRequest`): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.ExportAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified agent to a ZIP file. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ExportAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.ImportAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ImportAgentRequest`): - The request object. The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.RestoreAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.RestoreAgentRequest`): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.GetValidationResultRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetValidationResultRequest`): - The request object. The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 a0da3d0e7..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py +++ /dev/null @@ -1,1112 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AgentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AgentsTransport): - # transport is a AgentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def get_agent(self, - request: agent.GetAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.GetAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_agent.SetAgentRequest = None, - *, - agent: gcd_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.SetAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: agent.DeleteAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.SearchAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (google.cloud.dialogflow_v2.types.SearchAgentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.TrainAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.TrainAgentRequest): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.ExportAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified agent to a ZIP file. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.ExportAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.ImportAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (google.cloud.dialogflow_v2.types.ImportAgentRequest): - The request object. The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.RestoreAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (google.cloud.dialogflow_v2.types.RestoreAgentRequest): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.GetValidationResultRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.GetValidationResultRequest): - The request object. The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 5ef3d2074..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 0dc0c06c1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] -_transport_registry['grpc'] = AgentsGrpcTransport -_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport - -__all__ = ( - 'AgentsTransport', - 'AgentsGrpcTransport', - 'AgentsGrpcAsyncIOTransport', -) 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 6185b62fe..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py +++ /dev/null @@ -1,305 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import agent -from google.cloud.dialogflow_v2.types import agent as gcd_agent -from google.cloud.dialogflow_v2.types import validation_result -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 7890e85fc..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py +++ /dev/null @@ -1,522 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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'] - - -__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 beedb258f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,526 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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'] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) 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 16c67859b..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 33c4bc1a1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ /dev/null @@ -1,370 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.answer_records import pagers -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", - client_options: 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: answer_record.ListAnswerRecordsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsAsyncPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_answer_record.UpdateAnswerRecordRequest = None, - *, - answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 8b4317a5b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py +++ /dev/null @@ -1,557 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.answer_records import pagers -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AnswerRecordsGrpcTransport -from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AnswerRecordsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AnswerRecordsTransport): - # transport is a AnswerRecordsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_answer_records(self, - request: answer_record.ListAnswerRecordsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - Args: - request (google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_answer_record.UpdateAnswerRecordRequest = None, - *, - answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 1e86c11ca..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 99c08cf37..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] -_transport_registry['grpc'] = AnswerRecordsGrpcTransport -_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport - -__all__ = ( - 'AnswerRecordsTransport', - 'AnswerRecordsGrpcTransport', - 'AnswerRecordsGrpcAsyncIOTransport', -) 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 238ccec6d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py +++ /dev/null @@ -1,198 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 13aaaa972..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py +++ /dev/null @@ -1,277 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 1e168c246..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py +++ /dev/null @@ -1,281 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .grpc import AnswerRecordsGrpcTransport - - -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'AnswerRecordsGrpcAsyncIOTransport', -) 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 b0d60f297..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 476b7c3e4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py +++ /dev/null @@ -1,703 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.contexts import pagers -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ContextsTransport] = "grpc_asyncio", - client_options: 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: context.ListContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsAsyncPager: - r"""Returns the list of all contexts in the specified - session. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListContextsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: context.GetContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_context.CreateContextRequest = None, - *, - parent: str = None, - context: gcd_context.Context = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, - *, - context: gcd_context.Context = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: context.DeleteContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: context.DeleteAllContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteAllContextsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 7081d027b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py +++ /dev/null @@ -1,890 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.contexts import pagers -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import field_mask_pb2 # 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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ContextsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ContextsTransport): - # transport is a ContextsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_contexts(self, - request: context.ListContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsPager: - r"""Returns the list of all contexts in the specified - session. - - Args: - request (google.cloud.dialogflow_v2.types.ListContextsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: context.GetContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - Args: - request (google.cloud.dialogflow_v2.types.GetContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_context.CreateContextRequest = None, - *, - parent: str = None, - context: gcd_context.Context = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - Args: - request (google.cloud.dialogflow_v2.types.CreateContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, - *, - context: gcd_context.Context = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: context.DeleteContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: context.DeleteAllContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteAllContextsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 8b13d41ab..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 eb854f545..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] -_transport_registry['grpc'] = ContextsGrpcTransport -_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport - -__all__ = ( - 'ContextsTransport', - 'ContextsGrpcTransport', - 'ContextsGrpcAsyncIOTransport', -) 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 e9533fa3e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py +++ /dev/null @@ -1,255 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 8884de505..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py +++ /dev/null @@ -1,383 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 d258d4aaf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py +++ /dev/null @@ -1,387 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'ContextsGrpcAsyncIOTransport', -) 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 3e8e4ea19..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 c2c835023..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py +++ /dev/null @@ -1,594 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.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.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) - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", - client_options: 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: conversation_profile.ListConversationProfilesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesAsyncPager: - r"""Returns the list of all conversation profiles in the - specified project. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListConversationProfilesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation_profile.GetConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_conversation_profile.CreateConversationProfileRequest = None, - *, - parent: str = None, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, - *, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 dba48424b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py +++ /dev/null @@ -1,817 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.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.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 - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationProfilesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationProfilesTransport): - # transport is a ConversationProfilesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_conversation_profiles(self, - request: conversation_profile.ListConversationProfilesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesPager: - r"""Returns the list of all conversation profiles in the - specified project. - - Args: - request (google.cloud.dialogflow_v2.types.ListConversationProfilesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation_profile.GetConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - Args: - request (google.cloud.dialogflow_v2.types.GetConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_conversation_profile.CreateConversationProfileRequest = None, - *, - parent: str = None, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.CreateConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, - *, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - Args: - request (google.cloud.dialogflow_v2.types.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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 65ef11f7a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 19a679f49..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] -_transport_registry['grpc'] = ConversationProfilesGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport - -__all__ = ( - 'ConversationProfilesTransport', - 'ConversationProfilesGrpcTransport', - 'ConversationProfilesGrpcAsyncIOTransport', -) 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 f280996cf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 0f8cc8e8e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py +++ /dev/null @@ -1,368 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 02088afc8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py +++ /dev/null @@ -1,372 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'ConversationProfilesGrpcAsyncIOTransport', -) 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 0445da9c4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 872f9d3bb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ /dev/null @@ -1,625 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.conversations import pagers -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 # 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 - - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ConversationsTransport] = "grpc_asyncio", - client_options: 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: gcd_conversation.CreateConversationRequest = None, - *, - parent: str = None, - conversation: gcd_conversation.Conversation = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Returns the list of all conversations in the - specified project. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListConversationsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.GetConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.CompleteConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CompleteConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.ListMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListMessagesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 80ec8e11e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py +++ /dev/null @@ -1,830 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.conversations import pagers -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationsGrpcTransport -from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationsTransport): - # transport is a ConversationsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_conversation(self, - request: gcd_conversation.CreateConversationRequest = None, - *, - parent: str = None, - conversation: gcd_conversation.Conversation = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.CreateConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Returns the list of all conversations in the - specified project. - - Args: - request (google.cloud.dialogflow_v2.types.ListConversationsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.GetConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - Args: - request (google.cloud.dialogflow_v2.types.GetConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.CompleteConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Args: - request (google.cloud.dialogflow_v2.types.CompleteConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.ListMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.ListMessagesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 b102ea98e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py +++ /dev/null @@ -1,263 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 9d9ee9030..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] -_transport_registry['grpc'] = ConversationsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport - -__all__ = ( - 'ConversationsTransport', - 'ConversationsGrpcTransport', - 'ConversationsGrpcAsyncIOTransport', -) 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 db30b0301..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py +++ /dev/null @@ -1,240 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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, - ), - } - - @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() - - -__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 42e3f8764..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py +++ /dev/null @@ -1,381 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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'] - - -__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 06141f8fd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py +++ /dev/null @@ -1,385 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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'] - - -__all__ = ( - 'ConversationsGrpcAsyncIOTransport', -) 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 cee70ad81..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 4748c2c80..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py +++ /dev/null @@ -1,773 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, DocumentsTransport] = "grpc_asyncio", - client_options: 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: document.ListDocumentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Returns the list of all documents of the knowledge - base. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListDocumentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: document.GetDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_document.CreateDocumentRequest = None, - *, - parent: str = None, - document: gcd_document.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new document. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 delete_document(self, - request: document.DeleteDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified document. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteDocumentRequest`): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_document.UpdateDocumentRequest = None, - *, - document: gcd_document.Document = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified document. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: document.ReloadDocumentRequest = None, - *, - name: str = None, - content_uri: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ReloadDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 914f8bbab..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py +++ /dev/null @@ -1,960 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentsTransport): - # transport is a DocumentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_documents(self, - request: document.ListDocumentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Returns the list of all documents of the knowledge - base. - - Args: - request (google.cloud.dialogflow_v2.types.ListDocumentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: document.GetDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - Args: - request (google.cloud.dialogflow_v2.types.GetDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_document.CreateDocumentRequest = None, - *, - parent: str = None, - document: gcd_document.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new document. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.CreateDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 delete_document(self, - request: document.DeleteDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified document. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.DeleteDocumentRequest): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_document.UpdateDocumentRequest = None, - *, - document: gcd_document.Document = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the specified document. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.UpdateDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: document.ReloadDocumentRequest = None, - *, - name: str = None, - content_uri: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.ReloadDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 1d2c160be..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 f9ae67be5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] -_transport_registry['grpc'] = DocumentsGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport - -__all__ = ( - 'DocumentsTransport', - 'DocumentsGrpcTransport', - 'DocumentsGrpcAsyncIOTransport', -) 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 a29fbca95..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py +++ /dev/null @@ -1,261 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import document -from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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.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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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 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() - - -__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 6738b9bf5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py +++ /dev/null @@ -1,423 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - Operation - - 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 delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete document method over gRPC. - - Deletes the specified document. - - Operation - - 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. - - Operation - - 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. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Operation - - 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'] - - -__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 d74d21a45..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py +++ /dev/null @@ -1,427 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - Operation - - 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 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. - - Operation - - 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. - - Operation - - 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. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Operation - - 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'] - - -__all__ = ( - 'DocumentsGrpcAsyncIOTransport', -) 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 82dfe86fd..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 872034477..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py +++ /dev/null @@ -1,1195 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, EntityTypesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: entity_type.ListEntityTypesRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesAsyncPager: - r"""Returns the list of all entity types in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListEntityTypesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: entity_type.BatchUpdateEntityTypesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple entity types in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest`): - The request object. The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: entity_type.BatchDeleteEntityTypesRequest = None, - *, - parent: str = None, - entity_type_names: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entity types in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates multiple new entities in the specified entity type. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, - *, - parent: str = None, - entity_values: Sequence[str] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entities in the specified entity type. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 4b0947dcf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py +++ /dev/null @@ -1,1383 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EntityTypesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EntityTypesTransport): - # transport is a EntityTypesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_entity_types(self, - request: entity_type.ListEntityTypesRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesPager: - r"""Returns the list of all entity types in the specified - agent. - - Args: - request (google.cloud.dialogflow_v2.types.ListEntityTypesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - Args: - request (google.cloud.dialogflow_v2.types.GetEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.CreateEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: entity_type.BatchUpdateEntityTypesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple entity types in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest): - The request object. The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: entity_type.BatchDeleteEntityTypesRequest = None, - *, - parent: str = None, - entity_type_names: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entity types in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates multiple new entities in the specified entity type. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, - *, - parent: str = None, - entity_values: Sequence[str] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entities in the specified entity type. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 2e03a613e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 1a2aa82dc..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] -_transport_registry['grpc'] = EntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport - -__all__ = ( - 'EntityTypesTransport', - 'EntityTypesGrpcTransport', - 'EntityTypesGrpcAsyncIOTransport', -) 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 d6012fae0..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py +++ /dev/null @@ -1,318 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import entity_type -from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 50e9c62bb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py +++ /dev/null @@ -1,522 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__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 cdc5c9abe..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,526 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) 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 a3ad29ecd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 c3d227664..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py +++ /dev/null @@ -1,607 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.environments import pagers -from google.cloud.dialogflow_v2.types import environment -from google.cloud.dialogflow_v2.types import fulfillment -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - - -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) - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: environment.ListEnvironmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsAsyncPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListEnvironmentsRequest`): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - parent (:class:`str`): - Required. The agent to list all environments from. - Format: - - - ``projects//agent`` - - ``projects//locations//agent`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = environment.ListEnvironmentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - 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: environment.GetEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentRequest`): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.GetEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_environment(self, - request: environment.CreateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateEnvironmentRequest`): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.CreateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: environment.UpdateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Updates the specified agent environment. - - This method allows you to deploy new agent versions into the - environment. When an environment is pointed to a new agent - version by setting ``environment.agent_version``, the - environment is temporarily set to the ``LOADING`` state. During - that time, the environment keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest`): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.UpdateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment.name", request.environment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest`): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - request = environment.DeleteEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_environment_history(self, - request: environment.GetEnvironmentHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryAsyncPager: - r"""Gets the history of the specified environment. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest`): - The request object. The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = environment.GetEnvironmentHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment_history, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GetEnvironmentHistoryAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 ea085afd9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py +++ /dev/null @@ -1,808 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.environments import pagers -from google.cloud.dialogflow_v2.types import environment -from google.cloud.dialogflow_v2.types import fulfillment -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_environments(self, - request: environment.ListEnvironmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.ListEnvironmentsRequest): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - parent (str): - Required. The agent to list all environments from. - Format: - - - ``projects//agent`` - - ``projects//locations//agent`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a environment.ListEnvironmentsRequest. - # 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: environment.GetEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - Args: - request (google.cloud.dialogflow_v2.types.GetEnvironmentRequest): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.GetEnvironmentRequest): - request = environment.GetEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_environment(self, - request: environment.CreateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - Args: - request (google.cloud.dialogflow_v2.types.CreateEnvironmentRequest): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.CreateEnvironmentRequest): - request = environment.CreateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: environment.UpdateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Updates the specified agent environment. - - This method allows you to deploy new agent versions into the - environment. When an environment is pointed to a new agent - version by setting ``environment.agent_version``, the - environment is temporarily set to the ``LOADING`` state. During - that time, the environment keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.UpdateEnvironmentRequest): - request = environment.UpdateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment.name", request.environment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.DeleteEnvironmentRequest): - request = environment.DeleteEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_environment_history(self, - request: environment.GetEnvironmentHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryPager: - r"""Gets the history of the specified environment. - - Args: - request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): - The request object. The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.GetEnvironmentHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.GetEnvironmentHistoryRequest): - request = environment.GetEnvironmentHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_environment_history] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GetEnvironmentHistoryPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 a9efd221e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py +++ /dev/null @@ -1,262 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[environment.EnvironmentHistory]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: - for page in self.pages: - yield from page.entries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GetEnvironmentHistoryAsyncPager: - """A pager for iterating through ``get_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and - provides an ``__aiter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GetEnvironmentHistory`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[environment.EnvironmentHistory]], - request: environment.GetEnvironmentHistoryRequest, - response: environment.EnvironmentHistory, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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) -> AsyncIterable[environment.EnvironmentHistory]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: - async def async_generator(): - async for page in self.pages: - for response in page.entries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 fac90efe0..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', -) 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 945470a49..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py +++ /dev/null @@ -1,254 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import environment -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_environments: gapic_v1.method.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.create_environment: gapic_v1.method.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment_history: gapic_v1.method.wrap_method( - self.get_environment_history, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_environments(self) -> 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() - - -__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 d7a329652..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py +++ /dev/null @@ -1,393 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import environment -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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.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 keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - ~.Environment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', - request_serializer=environment.UpdateEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete environment method over gRPC. - - Deletes the specified agent environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_environment' not in self._stubs: - self._stubs['delete_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def get_environment_history(self) -> Callable[ - [environment.GetEnvironmentHistoryRequest], - environment.EnvironmentHistory]: - r"""Return a callable for the get environment history method over gRPC. - - Gets the history of the specified environment. - - Returns: - Callable[[~.GetEnvironmentHistoryRequest], - ~.EnvironmentHistory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_environment_history' not in self._stubs: - self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', - request_serializer=environment.GetEnvironmentHistoryRequest.serialize, - response_deserializer=environment.EnvironmentHistory.deserialize, - ) - return self._stubs['get_environment_history'] - - -__all__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/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 4a2617127..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,397 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import environment -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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.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 keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - Awaitable[~.Environment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', - request_serializer=environment.UpdateEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete environment method over gRPC. - - Deletes the specified agent environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_environment' not in self._stubs: - self._stubs['delete_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def get_environment_history(self) -> Callable[ - [environment.GetEnvironmentHistoryRequest], - Awaitable[environment.EnvironmentHistory]]: - r"""Return a callable for the get environment history method over gRPC. - - Gets the history of the specified environment. - - Returns: - Callable[[~.GetEnvironmentHistoryRequest], - Awaitable[~.EnvironmentHistory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_environment_history' not in self._stubs: - self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', - request_serializer=environment.GetEnvironmentHistoryRequest.serialize, - response_deserializer=environment.EnvironmentHistory.deserialize, - ) - return self._stubs['get_environment_history'] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/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 8204500fb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 bf8a73421..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py +++ /dev/null @@ -1,871 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, IntentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: intent.ListIntentsRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsAsyncPager: - r"""Returns the list of all intents in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListIntentsRequest`): - 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``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcd_intent.Intent = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, - *, - intent: gcd_intent.Intent = None, - language_code: str = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: intent.DeleteIntentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or - indirect followup intents. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: intent.BatchUpdateIntentsRequest = None, - *, - parent: str = None, - intent_batch_uri: str = None, - intent_batch_inline: intent.IntentBatch = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple intents in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, - *, - parent: str = None, - intents: Sequence[intent.Intent] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes intents in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 cff8eaaa3..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py +++ /dev/null @@ -1,1067 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, IntentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, IntentsTransport): - # transport is a IntentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_intents(self, - request: intent.ListIntentsRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsPager: - r"""Returns the list of all intents in the specified - agent. - - Args: - request (google.cloud.dialogflow_v2.types.ListIntentsRequest): - 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``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - Args: - request (google.cloud.dialogflow_v2.types.GetIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcd_intent.Intent = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.CreateIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, - *, - intent: gcd_intent.Intent = None, - language_code: str = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: intent.DeleteIntentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or - indirect followup intents. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: intent.BatchUpdateIntentsRequest = None, - *, - parent: str = None, - intent_batch_uri: str = None, - intent_batch_inline: intent.IntentBatch = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple intents in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, - *, - parent: str = None, - intents: Sequence[intent.Intent] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes intents in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 cdb3d2195..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 aa8039bba..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] -_transport_registry['grpc'] = IntentsGrpcTransport -_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport - -__all__ = ( - 'IntentsTransport', - 'IntentsGrpcTransport', - 'IntentsGrpcAsyncIOTransport', -) 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 980268863..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py +++ /dev/null @@ -1,276 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import intent -from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 ea2071352..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py +++ /dev/null @@ -1,433 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__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 e3ef04fd5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py +++ /dev/null @@ -1,437 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) 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 670d8e66d..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 686912fe9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py +++ /dev/null @@ -1,601 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.knowledge_bases import pagers -from google.cloud.dialogflow_v2.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", - client_options: 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: knowledge_base.ListKnowledgeBasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesAsyncPager: - r"""Returns the list of all knowledge bases of the - specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: knowledge_base.GetKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, - *, - parent: str = None, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, - *, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 2a303b953..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py +++ /dev/null @@ -1,788 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.knowledge_bases import pagers -from google.cloud.dialogflow_v2.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import KnowledgeBasesGrpcTransport -from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, KnowledgeBasesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, KnowledgeBasesTransport): - # transport is a KnowledgeBasesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_knowledge_bases(self, - request: knowledge_base.ListKnowledgeBasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesPager: - r"""Returns the list of all knowledge bases of the - specified agent. - - Args: - request (google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: knowledge_base.GetKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - Args: - request (google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, - *, - parent: str = None, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - Args: - request (google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, - *, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 479130853..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 c04ef7c9f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] -_transport_registry['grpc'] = KnowledgeBasesGrpcTransport -_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport - -__all__ = ( - 'KnowledgeBasesTransport', - 'KnowledgeBasesGrpcTransport', - 'KnowledgeBasesGrpcAsyncIOTransport', -) 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 d50f63144..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 3872d90fa..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py +++ /dev/null @@ -1,356 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 270cf1ffa..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py +++ /dev/null @@ -1,360 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'KnowledgeBasesGrpcAsyncIOTransport', -) 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 376e9e7d4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 aa70ac524..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py +++ /dev/null @@ -1,766 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.participants import pagers -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -from google.cloud.dialogflow_v2.types import session -from google.protobuf import field_mask_pb2 # 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 - - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ParticipantsTransport] = "grpc_asyncio", - client_options: 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: gcd_participant.CreateParticipantRequest = None, - *, - parent: str = None, - participant: gcd_participant.Participant = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.ListParticipantsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsAsyncPager: - r"""Returns the list of all participants in the specified - conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListParticipantsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_participant.UpdateParticipantRequest = None, - *, - participant: gcd_participant.Participant = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, - *, - participant: str = None, - text_input: session.TextInput = None, - event_input: session.EventInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.AnalyzeContentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - async def suggest_articles(self, - request: participant.SuggestArticlesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on - specific historical messages. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.SuggestArticlesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.SuggestFaqAnswersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 826119b07..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py +++ /dev/null @@ -1,983 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.participants import pagers -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -from google.cloud.dialogflow_v2.types import session -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ParticipantsGrpcTransport -from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ParticipantsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ParticipantsTransport): - # transport is a ParticipantsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_participant(self, - request: gcd_participant.CreateParticipantRequest = None, - *, - parent: str = None, - participant: gcd_participant.Participant = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - Args: - request (google.cloud.dialogflow_v2.types.CreateParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - Args: - request (google.cloud.dialogflow_v2.types.GetParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.ListParticipantsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsPager: - r"""Returns the list of all participants in the specified - conversation. - - Args: - request (google.cloud.dialogflow_v2.types.ListParticipantsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_participant.UpdateParticipantRequest = None, - *, - participant: gcd_participant.Participant = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, - *, - participant: str = None, - text_input: session.TextInput = None, - event_input: session.EventInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (google.cloud.dialogflow_v2.types.AnalyzeContentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 suggest_articles(self, - request: participant.SuggestArticlesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on - specific historical messages. - - Args: - request (google.cloud.dialogflow_v2.types.SuggestArticlesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.SuggestFaqAnswersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - Args: - request (google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 f4bea5ed9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 e30c79b00..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] -_transport_registry['grpc'] = ParticipantsGrpcTransport -_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport - -__all__ = ( - 'ParticipantsTransport', - 'ParticipantsGrpcTransport', - 'ParticipantsGrpcAsyncIOTransport', -) 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 15cd248da..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py +++ /dev/null @@ -1,274 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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, - ), - } - - @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 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() - - -__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 645ac0c78..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py +++ /dev/null @@ -1,414 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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 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'] - - -__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 f963f52d9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py +++ /dev/null @@ -1,418 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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'] - - -__all__ = ( - 'ParticipantsGrpcAsyncIOTransport', -) 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 fb6678b14..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 f393102a1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py +++ /dev/null @@ -1,629 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: session_entity_type.ListSessionEntityTypesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: session_entity_type.GetSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 a74bf29b6..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py +++ /dev/null @@ -1,816 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.services.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionEntityTypesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SessionEntityTypesTransport): - # transport is a SessionEntityTypesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_session_entity_types(self, - request: session_entity_type.ListSessionEntityTypesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: session_entity_type.GetSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 df1a4f275..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 fee526724..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] -_transport_registry['grpc'] = SessionEntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport - -__all__ = ( - 'SessionEntityTypesTransport', - 'SessionEntityTypesGrpcTransport', - 'SessionEntityTypesGrpcAsyncIOTransport', -) 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 704dae441..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 d367539aa..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py +++ /dev/null @@ -1,374 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 f38327593..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,378 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'SessionEntityTypesGrpcAsyncIOTransport', -) 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 92490cc5a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 b2239cea8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ /dev/null @@ -1,396 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, SessionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: gcd_session.DetectIntentRequest = None, - *, - session: str = None, - query_input: gcd_session.QueryInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DetectIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: AsyncIterator[session.StreamingDetectIntentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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). - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - 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 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. 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 e325e64ab..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py +++ /dev/null @@ -1,600 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 # type: ignore -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SessionsGrpcTransport -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SessionsTransport): - # transport is a SessionsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def detect_intent(self, - request: gcd_session.DetectIntentRequest = None, - *, - session: str = None, - query_input: gcd_session.QueryInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Args: - request (google.cloud.dialogflow_v2.types.DetectIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: Iterator[session.StreamingDetectIntentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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). - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - 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 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. 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 fde19f616..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] -_transport_registry['grpc'] = SessionsGrpcTransport -_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport - -__all__ = ( - 'SessionsTransport', - 'SessionsGrpcTransport', - 'SessionsGrpcAsyncIOTransport', -) 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 74789f356..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py +++ /dev/null @@ -1,204 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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, - ), - } - - @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() - - -__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 0821b615a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py +++ /dev/null @@ -1,292 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - - 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). - - 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'] - - -__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 c7b313261..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,296 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - - 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). - - 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'] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) 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 3656d3519..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py +++ /dev/null @@ -1,398 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, - VoiceSelectionParams, - AudioEncoding, - OutputAudioEncoding, - SpeechModelVariant, - SsmlVoiceGender, -) -from .context import ( - Context, - CreateContextRequest, - DeleteAllContextsRequest, - DeleteContextRequest, - GetContextRequest, - ListContextsRequest, - ListContextsResponse, - UpdateContextRequest, -) -from .conversation import ( - CompleteConversationRequest, - Conversation, - ConversationPhoneNumber, - CreateConversationRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - ListMessagesRequest, - ListMessagesResponse, -) -from .conversation_event import ( - ConversationEvent, -) -from .conversation_profile import ( - AutomatedAgentConfig, - ConversationProfile, - CreateConversationProfileRequest, - DeleteConversationProfileRequest, - GetConversationProfileRequest, - HumanAgentAssistantConfig, - HumanAgentHandoffConfig, - ListConversationProfilesRequest, - ListConversationProfilesResponse, - LoggingConfig, - NotificationConfig, - SuggestionFeature, - UpdateConversationProfileRequest, -) -from .document import ( - CreateDocumentRequest, - DeleteDocumentRequest, - Document, - GetDocumentRequest, - 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 .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, - AutomatedAgentReply, - CreateParticipantRequest, - DtmfParameters, - FaqAnswer, - GetParticipantRequest, - ListParticipantsRequest, - ListParticipantsResponse, - Message, - MessageAnnotation, - OutputAudio, - Participant, - SuggestArticlesRequest, - SuggestArticlesResponse, - SuggestFaqAnswersRequest, - SuggestFaqAnswersResponse, - SuggestionResult, - 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', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SuggestionFeature', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'GetDocumentRequest', - 'KnowledgeOperationMetadata', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'ReloadDocumentRequest', - 'UpdateDocumentRequest', - 'BatchCreateEntitiesRequest', - 'BatchDeleteEntitiesRequest', - 'BatchDeleteEntityTypesRequest', - 'BatchUpdateEntitiesRequest', - 'BatchUpdateEntityTypesRequest', - 'BatchUpdateEntityTypesResponse', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'EntityTypeBatch', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'EnvironmentHistory', - 'GetEnvironmentHistoryRequest', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'TextToSpeechSettings', - 'UpdateEnvironmentRequest', - 'Fulfillment', - 'GetFulfillmentRequest', - 'UpdateFulfillmentRequest', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AutomatedAgentReply', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestionResult', - '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 736fe28e5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py +++ /dev/null @@ -1,459 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - '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 (Sequence[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. - """ - MATCH_MODE_UNSPECIFIED = 0 - MATCH_MODE_HYBRID = 1 - MATCH_MODE_ML_ONLY = 2 - - class ApiVersion(proto.Enum): - r"""API version for the agent.""" - 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.""" - TIER_UNSPECIFIED = 0 - TIER_STANDARD = 1 - TIER_ENTERPRISE = 2 - TIER_ENTERPRISE_PLUS = 3 - - parent = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - default_language_code = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri = proto.Field( - proto.STRING, - number=7, - ) - enable_logging = proto.Field( - proto.BOOL, - number=8, - ) - match_mode = proto.Field( - proto.ENUM, - number=9, - enum=MatchMode, - ) - classification_threshold = proto.Field( - proto.FLOAT, - number=10, - ) - api_version = proto.Field( - proto.ENUM, - number=14, - enum=ApiVersion, - ) - tier = proto.Field( - proto.ENUM, - number=15, - enum=Tier, - ) - - -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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Agent', - ) - update_mask = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchAgentsResponse(proto.Message): - r"""The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - Attributes: - agents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Agent', - ) - next_page_token = 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 = 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - - 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``. - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - agent_uri = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class ImportAgentRequest(proto.Message): - r"""The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - - 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://". - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - - 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://". - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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 9eaf196f5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py +++ /dev/null @@ -1,350 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - answer_feedback = proto.Field( - proto.MESSAGE, - number=2, - message='AnswerFeedback', - ) - agent_assistant_record = proto.Field( - proto.MESSAGE, - number=4, - oneof='record', - message='AgentAssistantRecord', - ) - - -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): - Required. Filters to restrict results to specific answer - records. Filter on answer record type. Currently predicates - on ``type`` is supported, valid values are - ``ARTICLE_ANSWER``, ``FAQ_ANSWER``. - - 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 = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnswerRecordsResponse(proto.Message): - r"""Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - Attributes: - answer_records (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - next_page_token = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - update_mask = 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. - - 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. - 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.""" - CORRECTNESS_LEVEL_UNSPECIFIED = 0 - NOT_CORRECT = 1 - PARTIALLY_CORRECT = 2 - FULLY_CORRECT = 3 - - correctness_level = proto.Field( - proto.ENUM, - number=1, - enum=CorrectnessLevel, - ) - agent_assistant_detail_feedback = proto.Field( - proto.MESSAGE, - number=2, - oneof='detail_feedback', - message='AgentAssistantFeedback', - ) - clicked = proto.Field( - proto.BOOL, - number=3, - ) - click_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - displayed = proto.Field( - proto.BOOL, - number=4, - ) - display_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class AgentAssistantFeedback(proto.Message): - r"""Detail feedback of Agent Assist result. - Attributes: - answer_relevance (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.AnswerRelevance): - Optional. Whether or not the suggested answer is relevant. - - 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]. - """ - class AnswerRelevance(proto.Enum): - r"""Relevance of an answer.""" - ANSWER_RELEVANCE_UNSPECIFIED = 0 - IRRELEVANT = 1 - RELEVANT = 2 - - class DocumentCorrectness(proto.Enum): - r"""Correctness of document.""" - DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 - INCORRECT = 1 - CORRECT = 2 - - class DocumentEfficiency(proto.Enum): - r"""Efficiency of document.""" - DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 - INEFFICIENT = 1 - EFFICIENT = 2 - - answer_relevance = proto.Field( - proto.ENUM, - number=1, - enum=AnswerRelevance, - ) - document_correctness = proto.Field( - proto.ENUM, - number=2, - enum=DocumentCorrectness, - ) - document_efficiency = proto.Field( - proto.ENUM, - number=3, - enum=DocumentEfficiency, - ) - - -class AgentAssistantRecord(proto.Message): - r"""Represents a record of a human agent assist answer. - Attributes: - article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): - Output only. The article suggestion answer. - faq_answer (google.cloud.dialogflow_v2.types.FaqAnswer): - Output only. The FAQ answer. - """ - - article_suggestion_answer = proto.Field( - proto.MESSAGE, - number=5, - oneof='answer', - message=participant.ArticleAnswer, - ) - faq_answer = proto.Field( - proto.MESSAGE, - number=6, - oneof='answer', - message=participant.FaqAnswer, - ) - - -__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 719655107..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py +++ /dev/null @@ -1,463 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'AudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'OutputAudioEncoding', - 'SpeechContext', - 'SpeechWordInfo', - 'InputAudioConfig', - 'VoiceSelectionParams', - 'SynthesizeSpeechConfig', - 'OutputAudioConfig', - '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. - """ - 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. - """ - 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 `__. - """ - 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.""" - 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 SpeechContext(proto.Message): - r"""Hints for the speech recognizer to help with recognition in a - specific conversation state. - - Attributes: - phrases (Sequence[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 = proto.RepeatedField( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - -class SpeechWordInfo(proto.Message): - r"""Information for a word recognized by the speech recognizer. - Attributes: - word (str): - The word this info is for. - 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 = proto.Field( - proto.STRING, - number=3, - ) - start_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - -class InputAudioConfig(proto.Message): - 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 (Sequence[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 (Sequence[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 = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - enable_word_info = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints = proto.RepeatedField( - proto.STRING, - number=4, - ) - speech_contexts = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechContext', - ) - model = proto.Field( - proto.STRING, - number=7, - ) - model_variant = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance = proto.Field( - proto.BOOL, - number=8, - ) - disable_no_speech_recognized_event = proto.Field( - proto.BOOL, - number=14, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - ssml_gender = proto.Field( - proto.ENUM, - number=2, - enum='SsmlVoiceGender', - ) - - -class SynthesizeSpeechConfig(proto.Message): - r"""Configuration of how speech should be synthesized. - Attributes: - speaking_rate (float): - Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 - 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 (Sequence[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 = proto.Field( - proto.DOUBLE, - number=1, - ) - pitch = proto.Field( - proto.DOUBLE, - number=2, - ) - volume_gain_db = proto.Field( - proto.DOUBLE, - number=3, - ) - effects_profile_id = proto.RepeatedField( - proto.STRING, - number=5, - ) - voice = proto.Field( - proto.MESSAGE, - number=4, - message='VoiceSelectionParams', - ) - - -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 = proto.Field( - proto.ENUM, - number=1, - enum='OutputAudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - synthesize_speech_config = proto.Field( - proto.MESSAGE, - number=3, - message='SynthesizeSpeechConfig', - ) - - -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): - Optional. 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. - """ - - speech_model_variant = proto.Field( - proto.ENUM, - number=1, - enum='SpeechModelVariant', - ) - - -__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 066ef0f13..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py +++ /dev/null @@ -1,298 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import 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 = proto.Field( - proto.STRING, - number=1, - ) - lifespan_count = proto.Field( - proto.INT32, - number=2, - ) - parameters = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -class ListContextsRequest(proto.Message): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListContextsResponse(proto.Message): - r"""The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - Attributes: - contexts (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Context', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Context', - ) - update_mask = 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 = 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 = 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 30727db67..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py +++ /dev/null @@ -1,390 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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', - }, -) - - -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.""" - 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 - """ - CONVERSATION_STAGE_UNSPECIFIED = 0 - VIRTUAL_AGENT_STAGE = 1 - HUMAN_ASSIST_STAGE = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - lifecycle_state = proto.Field( - proto.ENUM, - number=2, - enum=LifecycleState, - ) - conversation_profile = proto.Field( - proto.STRING, - number=3, - ) - phone_number = proto.Field( - proto.MESSAGE, - number=4, - message='ConversationPhoneNumber', - ) - start_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - conversation_stage = proto.Field( - proto.ENUM, - number=7, - enum=ConversationStage, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - conversation = proto.Field( - proto.MESSAGE, - number=2, - message='Conversation', - ) - conversation_id = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListConversationsResponse(proto.Message): - r"""The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - Attributes: - conversations (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Conversation', - ) - next_page_token = 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 = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListMessagesResponse(proto.Message): - r"""The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - Attributes: - messages (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=participant.Message, - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=3, - ) - - -__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 19e056323..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py +++ /dev/null @@ -1,79 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - - 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. - """ - class Type(proto.Enum): - r"""Enumeration of the types of events available.""" - TYPE_UNSPECIFIED = 0 - CONVERSATION_STARTED = 1 - CONVERSATION_FINISHED = 2 - HUMAN_INTERVENTION_NEEDED = 3 - NEW_MESSAGE = 5 - UNRECOVERABLE_ERROR = 4 - - conversation = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - error_status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - new_message_payload = 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_profile.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py deleted file mode 100644 index 5c9e5faab..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py +++ /dev/null @@ -1,834 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import audio_config -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', - }, -) - - -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 which represents the - conversationProfile. If unspecified, the default - language code en-us applies. Users need to - create a ConversationProfile for each language - they want to support. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - automated_agent_config = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentConfig', - ) - human_agent_assistant_config = proto.Field( - proto.MESSAGE, - number=4, - message='HumanAgentAssistantConfig', - ) - human_agent_handoff_config = proto.Field( - proto.MESSAGE, - number=5, - message='HumanAgentHandoffConfig', - ) - notification_config = proto.Field( - proto.MESSAGE, - number=6, - message='NotificationConfig', - ) - logging_config = proto.Field( - proto.MESSAGE, - number=7, - message='LoggingConfig', - ) - new_message_event_notification_config = proto.Field( - proto.MESSAGE, - number=8, - message='NotificationConfig', - ) - stt_config = proto.Field( - proto.MESSAGE, - number=9, - message=audio_config.SpeechToTextConfig, - ) - language_code = proto.Field( - proto.STRING, - number=10, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationProfilesResponse(proto.Message): - r"""The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - Attributes: - conversation_profiles (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - conversation_profile = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - update_mask = 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 = 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. - - Format: - ``projects//locations//agent/environments/``. - If environment is not specified, the default ``draft`` - environment is used. Refer to - `DetectIntentRequest `__ - for more details. - """ - - agent = proto.Field( - proto.STRING, - number=1, - ) - - -class HumanAgentAssistantConfig(proto.Message): - r"""Defines the Human Agent Assist to connect to a conversation. - Attributes: - notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): - Pub/Sub topic on which to publish new agent - 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 = proto.Field( - proto.BOOL, - number=1, - ) - only_end_user = proto.Field( - proto.BOOL, - number=2, - ) - - class SuggestionFeatureConfig(proto.Message): - r"""Config for suggestion features. - Attributes: - suggestion_feature (google.cloud.dialogflow_v2.types.SuggestionFeature): - The suggestion feature. - 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. - """ - - suggestion_feature = proto.Field( - proto.MESSAGE, - number=5, - message='SuggestionFeature', - ) - enable_event_based_suggestion = proto.Field( - proto.BOOL, - number=3, - ) - suggestion_trigger_settings = proto.Field( - proto.MESSAGE, - number=10, - message='HumanAgentAssistantConfig.SuggestionTriggerSettings', - ) - query_config = proto.Field( - proto.MESSAGE, - number=6, - message='HumanAgentAssistantConfig.SuggestionQueryConfig', - ) - conversation_model_config = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.ConversationModelConfig', - ) - - class SuggestionConfig(proto.Message): - r"""Detail human agent assistant config. - Attributes: - feature_configs (Sequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): - Configuration of different suggestion - 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 = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - group_suggestion_responses = proto.Field( - proto.BOOL, - number=3, - ) - - class SuggestionQueryConfig(proto.Message): - r"""Config for suggestion query. - Attributes: - knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): - Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, - FAQ. - document_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): - Query from knowledge base document. It is used by: - SMART_REPLY, SMART_COMPOSE. - dialogflow_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): - Query from Dialogflow agent. It is used by - DIALOGFLOW_ASSIST. - 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. - 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 (Sequence[str]): - Required. Knowledge bases to query. Format: - ``projects//locations//knowledgeBases/``. - Currently, at most 5 knowledge bases are supported. - """ - - knowledge_bases = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DocumentQuerySource(proto.Message): - r"""Document source settings. - - Supported features: SMART_REPLY, SMART_COMPOSE. - - Attributes: - documents (Sequence[str]): - Required. Knowledge documents to query from. Format: - ``projects//locations//knowledgeBases//documents/``. - Currently, at most 5 documents are supported. - """ - - documents = 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 = 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 = proto.Field( - proto.BOOL, - number=1, - ) - drop_virtual_agent_messages = proto.Field( - proto.BOOL, - number=2, - ) - drop_ivr_messages = proto.Field( - proto.BOOL, - number=3, - ) - - knowledge_base_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', - ) - document_query_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', - ) - dialogflow_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', - ) - max_results = proto.Field( - proto.INT32, - number=4, - ) - confidence_threshold = proto.Field( - proto.FLOAT, - number=5, - ) - context_filter_settings = 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. - - Attributes: - model (str): - Conversation model resource name. Format: - ``projects//conversationModels/``. - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - 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 = proto.Field( - proto.BOOL, - number=2, - ) - enable_sentiment_analysis = proto.Field( - proto.BOOL, - number=3, - ) - - notification_config = proto.Field( - proto.MESSAGE, - number=2, - message='NotificationConfig', - ) - human_agent_suggestion_config = proto.Field( - proto.MESSAGE, - number=3, - message=SuggestionConfig, - ) - end_user_suggestion_config = proto.Field( - proto.MESSAGE, - number=4, - message=SuggestionConfig, - ) - message_analysis_config = proto.Field( - proto.MESSAGE, - number=5, - message=MessageAnalysisConfig, - ) - - -class HumanAgentHandoffConfig(proto.Message): - r"""Defines the hand off to a live agent, typically on which - external agent service provider to connect to a conversation. - Currently, this feature is not general available, please contact - Google to get access. - - Attributes: - live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): - Uses LivePerson (https://www.liveperson.com). - salesforce_live_agent_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): - Uses Salesforce Live Agent. - """ - - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - deployment_id = proto.Field( - proto.STRING, - number=2, - ) - button_id = proto.Field( - proto.STRING, - number=3, - ) - endpoint_domain = proto.Field( - proto.STRING, - number=4, - ) - - live_person_config = proto.Field( - proto.MESSAGE, - number=1, - oneof='agent_service', - message=LivePersonConfig, - ) - salesforce_live_agent_config = proto.Field( - proto.MESSAGE, - number=2, - 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. - - Notification works for phone calls, if this topic either 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. - - 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.""" - MESSAGE_FORMAT_UNSPECIFIED = 0 - PROTO = 1 - JSON = 2 - - topic = proto.Field( - proto.STRING, - number=1, - ) - message_format = proto.Field( - proto.ENUM, - number=2, - enum=MessageFormat, - ) - - -class LoggingConfig(proto.Message): - r"""Defines logging behavior for conversation lifecycle events. - Attributes: - enable_stackdriver_logging (bool): - Whether to log conversation events like - [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 = 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.""" - TYPE_UNSPECIFIED = 0 - ARTICLE_SUGGESTION = 1 - FAQ = 2 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - - -__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 b10de177b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py +++ /dev/null @@ -1,372 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'Document', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'UpdateDocumentRequest', - 'ReloadDocumentRequest', - '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``. - - 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 (Sequence[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. - raw_content (bytes): - The raw content of the document. This field is only - permitted for EXTRACTIVE_QA and FAQ knowledge types. - 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 (Sequence[google.cloud.dialogflow_v2.types.Document.MetadataEntry]): - 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. - """ - class KnowledgeType(proto.Enum): - r"""The knowledge type of document content.""" - KNOWLEDGE_TYPE_UNSPECIFIED = 0 - FAQ = 1 - EXTRACTIVE_QA = 2 - ARTICLE_SUGGESTION = 3 - - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - mime_type = proto.Field( - proto.STRING, - number=3, - ) - knowledge_types = proto.RepeatedField( - proto.ENUM, - number=4, - enum=KnowledgeType, - ) - content_uri = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - raw_content = proto.Field( - proto.BYTES, - number=9, - oneof='source', - ) - enable_auto_reload = proto.Field( - proto.BOOL, - number=11, - ) - latest_reload_status = proto.Field( - proto.MESSAGE, - number=12, - message=ReloadStatus, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - - -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 = 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - Attributes: - documents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - document = proto.Field( - proto.MESSAGE, - number=2, - message='Document', - ) - - -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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Document', - ) - update_mask = 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]. - - 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:///``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - content_uri = proto.Field( - proto.STRING, - number=3, - oneof='source', - ) - - -class KnowledgeOperationMetadata(proto.Message): - r"""Metadata in google::longrunning::Operation for Knowledge - operations. - - Attributes: - state (google.cloud.dialogflow_v2.types.KnowledgeOperationMetadata.State): - Output only. The current state of this - operation. - """ - class State(proto.Enum): - r"""States of the operation.""" - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - DONE = 3 - - state = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - - -__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 1113deb6d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py +++ /dev/null @@ -1,561 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - '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 (Sequence[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.""" - 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). - """ - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Entity, - ) - enable_fuzzy_extraction = proto.Field( - proto.BOOL, - number=7, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.MESSAGE, - number=2, - message='EntityType', - ) - language_code = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='EntityType', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_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 = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - 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://". - entity_type_batch_inline (google.cloud.dialogflow_v2.types.EntityTypeBatch): - The collection of entity types 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type_batch_uri = proto.Field( - proto.STRING, - number=2, - oneof='entity_type_batch', - ) - entity_type_batch_inline = proto.Field( - proto.MESSAGE, - number=3, - oneof='entity_type_batch', - message='EntityTypeBatch', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class BatchUpdateEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - Attributes: - entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): - The collection of updated or created entity - types. - """ - - entity_types = 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 (Sequence[str]): - Required. The names entity types to delete. All names must - point to the same agent as ``parent``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entity_type_names = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entity_values = proto.RepeatedField( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class EntityTypeBatch(proto.Message): - r"""This message is a wrapper around a collection of entity - types. - - Attributes: - entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): - A collection of entity types. - """ - - entity_types = 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 b6f0292e9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py +++ /dev/null @@ -1,459 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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/`` - 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. - """ - STATE_UNSPECIFIED = 0 - STOPPED = 1 - LOADING = 2 - RUNNING = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - agent_version = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - text_to_speech_settings = proto.Field( - proto.MESSAGE, - number=7, - message='TextToSpeechSettings', - ) - fulfillment = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_fulfillment.Fulfillment, - ) - - -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 (Sequence[google.cloud.dialogflow_v2.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): - Optional. Configuration of how speech should - be synthesized, mapping from language - (https://cloud.google.com/dialogflow/docs/reference/language) - to SynthesizeSpeechConfig. - """ - - enable_text_to_speech = proto.Field( - proto.BOOL, - number=1, - ) - output_audio_encoding = proto.Field( - proto.ENUM, - number=2, - enum=audio_config.OutputAudioEncoding, - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=3, - ) - synthesize_speech_configs = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=audio_config.SynthesizeSpeechConfig, - ) - - -class ListEnvironmentsRequest(proto.Message): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - Attributes: - environments (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. - - Attributes: - name (str): - Required. The name of the environment. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. - - Attributes: - parent (str): - Required. The agent to create an environment for. Supported - formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - environment (google.cloud.dialogflow_v2.types.Environment): - Required. The environment to create. - environment_id (str): - Required. The unique id of the new - environment. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - environment_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. - - Attributes: - environment (google.cloud.dialogflow_v2.types.Environment): - Required. The environment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - allow_load_to_draft_and_discard_changes (bool): - Optional. This field is used to prevent accidental overwrite - of the draft environment, which is an operation that cannot - be undone. To confirm that the caller desires this - overwrite, this field must be explicitly set to true when - updating the draft environment (environment ID = ``-``). - """ - - environment = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_load_to_draft_and_discard_changes = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. - - Attributes: - name (str): - Required. The name of the environment to delete. / Format: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEnvironmentHistoryRequest(proto.Message): - r"""The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - - Attributes: - parent (str): - Required. The name of the environment to retrieve history - for. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - page_size (int): - Optional. The maximum number of items to - return in a single page. By default 100 and at - most 1000. - page_token (str): - Optional. The next_page_token value returned from a previous - list request. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class EnvironmentHistory(proto.Message): - r"""The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - - Attributes: - parent (str): - Output only. The name of the environment this history is - for. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - entries (Sequence[google.cloud.dialogflow_v2.types.EnvironmentHistory.Entry]): - Output only. The list of agent environments. There will be a - maximum number of items returned based on the page_size - field in the request. - next_page_token (str): - Output only. Token to retrieve the next page - of results, or empty if there are no more - results in the list. - """ - - class Entry(proto.Message): - r"""Represents an environment history entry. - Attributes: - agent_version (str): - The agent version loaded into this - environment history entry. - description (str): - The developer-provided description for this - environment history entry. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of this environment history - entry. - """ - - agent_version = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - @property - def raw_page(self): - return self - - parent = proto.Field( - proto.STRING, - number=1, - ) - entries = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Entry, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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 16651cf55..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py +++ /dev/null @@ -1,25 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - }, -) - - -__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 625acf227..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py +++ /dev/null @@ -1,61 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestion results payload that this - notification refers to. - """ - - conversation = proto.Field( - proto.STRING, - number=1, - ) - participant = proto.Field( - proto.STRING, - number=3, - ) - suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_participant.SuggestionResult, - ) - - -__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 4ef1e4beb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py +++ /dev/null @@ -1,1611 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - """ - 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 (Sequence[str]): - Optional. The list of context names required for this intent - to be triggered. Format: - ``projects//agent/sessions/-/contexts/``. - events (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.Intent.Parameter]): - Optional. The collection of parameters - associated with the intent. - messages (Sequence[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 (Sequence[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): - 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 (Sequence[google.cloud.dialogflow_v2.types.Intent.FollowupIntentInfo]): - 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.""" - 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 (Sequence[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.""" - 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - alias = proto.Field( - proto.STRING, - number=3, - ) - user_defined = proto.Field( - proto.BOOL, - number=4, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum='Intent.TrainingPhrase.Type', - ) - parts = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Intent.TrainingPhrase.Part', - ) - times_added_count = proto.Field( - proto.INT32, - number=4, - ) - - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - value = proto.Field( - proto.STRING, - number=3, - ) - default_value = proto.Field( - proto.STRING, - number=4, - ) - entity_type_display_name = proto.Field( - proto.STRING, - number=5, - ) - mandatory = proto.Field( - proto.BOOL, - number=6, - ) - prompts = proto.RepeatedField( - proto.STRING, - number=7, - ) - is_list = proto.Field( - proto.BOOL, - number=8, - ) - - class Message(proto.Message): - r"""A rich response message. Corresponds to the intent ``Response`` - field in the Dialogflow console. For more information, see `Rich - response - messages `__. - - Attributes: - text (google.cloud.dialogflow_v2.types.Intent.Message.Text): - The text response. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - The image response. - quick_replies (google.cloud.dialogflow_v2.types.Intent.Message.QuickReplies): - The quick replies response. - card (google.cloud.dialogflow_v2.types.Intent.Message.Card): - The card response. - payload (google.protobuf.struct_pb2.Struct): - A custom platform-specific response. - simple_responses (google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponses): - The voice and text-only responses for Actions - on Google. - basic_card (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard): - The basic card response for Actions on - Google. - suggestions (google.cloud.dialogflow_v2.types.Intent.Message.Suggestions): - The suggestion chips for Actions on Google. - link_out_suggestion (google.cloud.dialogflow_v2.types.Intent.Message.LinkOutSuggestion): - The link out suggestion chip for Actions on - Google. - list_select (google.cloud.dialogflow_v2.types.Intent.Message.ListSelect): - The list card response for Actions on Google. - carousel_select (google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect): - The carousel card response for Actions on - Google. - browse_carousel_card (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard): - Browse carousel card for Actions on Google. - table_card (google.cloud.dialogflow_v2.types.Intent.Message.TableCard): - Table card for Actions on Google. - media_content (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent): - The media content card for Actions on Google. - 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 `__. - """ - 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 (Sequence[str]): - Optional. The collection of the agent's - responses. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Image(proto.Message): - r"""The image response message. - Attributes: - image_uri (str): - Optional. The public URI to an image file. - accessibility_text (str): - Optional. A text description of the image to - be used for accessibility, e.g., screen readers. - """ - - image_uri = proto.Field( - proto.STRING, - number=1, - ) - accessibility_text = proto.Field( - proto.STRING, - number=2, - ) - - class QuickReplies(proto.Message): - r"""The quick replies response message. - Attributes: - title (str): - Optional. The title of the collection of - quick replies. - quick_replies (Sequence[str]): - Optional. The collection of quick replies. - """ - - title = proto.Field( - proto.STRING, - number=1, - ) - quick_replies = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Card(proto.Message): - r"""The card response message. - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - image_uri (str): - Optional. The public URI to an image file for - the card. - buttons (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - postback = proto.Field( - proto.STRING, - number=2, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - image_uri = proto.Field( - proto.STRING, - number=3, - ) - buttons = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.Card.Button', - ) - - class SimpleResponse(proto.Message): - r"""The simple response message containing speech or text. - Attributes: - text_to_speech (str): - One of text_to_speech or ssml must be provided. The plain - 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 = proto.Field( - proto.STRING, - number=1, - ) - ssml = proto.Field( - proto.STRING, - number=2, - ) - display_text = proto.Field( - proto.STRING, - number=3, - ) - - class SimpleResponses(proto.Message): - r"""The collection of simple response candidates. This message in - ``QueryResult.fulfillment_messages`` and - ``WebhookResponse.fulfillment_messages`` should contain only one - ``SimpleResponse``. - - Attributes: - simple_responses (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponse]): - Required. The list of simple responses. - """ - - simple_responses = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - open_uri_action = proto.Field( - proto.MESSAGE, - number=2, - message='Intent.Message.BasicCard.Button.OpenUriAction', - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - formatted_text = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - buttons = 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 = proto.Field( - proto.STRING, - number=1, - ) - - class Suggestions(proto.Message): - r"""The collection of suggestions. - Attributes: - suggestions (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): - Required. The list of suggested replies. - """ - - suggestions = 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 = proto.Field( - proto.STRING, - number=1, - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - - class ListSelect(proto.Message): - r"""The card for presenting a list of options to select from. - Attributes: - title (str): - Optional. The overall title of the list. - items (Sequence[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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - items = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.ListSelect.Item', - ) - subtitle = proto.Field( - proto.STRING, - number=3, - ) - - class CarouselSelect(proto.Message): - r"""The card for presenting a carousel of options to select from. - Attributes: - items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): - Required. Carousel items. - """ - - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - items = 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 (Sequence[str]): - Optional. A list of synonyms that can also be - used to trigger this item in dialog. - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class MediaContent(proto.Message): - r"""The media content card for Actions on Google. - Attributes: - media_type (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaType): - Optional. What type of media is the content - (ie "audio"). - media_objects (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaObject]): - Required. List of media objects. - """ - class ResponseMediaType(proto.Enum): - r"""Format of response media type.""" - RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 - AUDIO = 1 - - class ResponseMediaObject(proto.Message): - r"""Response media object for media content card. - 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. - icon (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. Icon to display above media - content. - content_url (str): - Required. Url where the media is stored. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - large_image = proto.Field( - proto.MESSAGE, - number=3, - oneof='image', - message='Intent.Message.Image', - ) - icon = proto.Field( - proto.MESSAGE, - number=4, - oneof='image', - message='Intent.Message.Image', - ) - content_url = proto.Field( - proto.STRING, - number=5, - ) - - media_type = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.MediaContent.ResponseMediaType', - ) - media_objects = 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 (Sequence[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. - """ - 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.""" - URL_TYPE_HINT_UNSPECIFIED = 0 - AMP_ACTION = 1 - AMP_CONTENT = 2 - - url = proto.Field( - proto.STRING, - number=1, - ) - url_type_hint = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', - ) - - open_uri_action = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - footer = proto.Field( - proto.STRING, - number=5, - ) - - items = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', - ) - image_display_options = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties]): - Optional. Display properties for the columns - in this table. - rows (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardRow]): - Optional. Rows in this table of data. - buttons (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): - Optional. List of buttons for the card. - """ - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - image = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.Image', - ) - column_properties = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.ColumnProperties', - ) - rows = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.TableCardRow', - ) - buttons = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Intent.Message.BasicCard.Button', - ) - - 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.""" - HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 - LEADING = 1 - CENTER = 2 - TRAILING = 3 - - header = proto.Field( - proto.STRING, - number=1, - ) - horizontal_alignment = 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 (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.TableCardCell', - ) - divider_after = 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 = proto.Field( - proto.STRING, - number=1, - ) - - text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='Intent.Message.Text', - ) - image = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Intent.Message.Image', - ) - quick_replies = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message='Intent.Message.QuickReplies', - ) - card = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message='Intent.Message.Card', - ) - payload = proto.Field( - proto.MESSAGE, - number=5, - oneof='message', - message=struct_pb2.Struct, - ) - simple_responses = proto.Field( - proto.MESSAGE, - number=7, - oneof='message', - message='Intent.Message.SimpleResponses', - ) - basic_card = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message='Intent.Message.BasicCard', - ) - suggestions = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message='Intent.Message.Suggestions', - ) - link_out_suggestion = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message='Intent.Message.LinkOutSuggestion', - ) - list_select = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message='Intent.Message.ListSelect', - ) - carousel_select = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message='Intent.Message.CarouselSelect', - ) - browse_carousel_card = proto.Field( - proto.MESSAGE, - number=22, - oneof='message', - message='Intent.Message.BrowseCarouselCard', - ) - table_card = proto.Field( - proto.MESSAGE, - number=23, - oneof='message', - message='Intent.Message.TableCard', - ) - media_content = proto.Field( - proto.MESSAGE, - number=24, - oneof='message', - message='Intent.Message.MediaContent', - ) - platform = proto.Field( - proto.ENUM, - number=6, - enum='Intent.Message.Platform', - ) - - class FollowupIntentInfo(proto.Message): - r"""Represents a single followup intent in the chain. - Attributes: - followup_intent_name (str): - The unique identifier of the followup intent. Format: - ``projects//agent/intents/``. - parent_followup_intent_name (str): - The unique identifier of the followup intent's parent. - Format: ``projects//agent/intents/``. - """ - - followup_intent_name = proto.Field( - proto.STRING, - number=1, - ) - parent_followup_intent_name = proto.Field( - proto.STRING, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - webhook_state = proto.Field( - proto.ENUM, - number=6, - enum=WebhookState, - ) - priority = proto.Field( - proto.INT32, - number=3, - ) - is_fallback = proto.Field( - proto.BOOL, - number=4, - ) - ml_disabled = proto.Field( - proto.BOOL, - number=19, - ) - live_agent_handoff = proto.Field( - proto.BOOL, - number=20, - ) - end_interaction = proto.Field( - proto.BOOL, - number=21, - ) - input_context_names = proto.RepeatedField( - proto.STRING, - number=7, - ) - events = proto.RepeatedField( - proto.STRING, - number=8, - ) - training_phrases = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=TrainingPhrase, - ) - action = proto.Field( - proto.STRING, - number=10, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=context.Context, - ) - reset_contexts = proto.Field( - proto.BOOL, - number=12, - ) - parameters = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Parameter, - ) - messages = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=Message, - ) - default_response_platforms = proto.RepeatedField( - proto.ENUM, - number=15, - enum=Message.Platform, - ) - root_followup_intent_name = proto.Field( - proto.STRING, - number=16, - ) - parent_followup_intent_name = proto.Field( - proto.STRING, - number=17, - ) - followup_intent_info = 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``. - 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - Attributes: - intents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = 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 = proto.Field( - proto.STRING, - number=1, - ) - intent = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - intent_view = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - intent_view = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateIntentsRequest(proto.Message): - r""" - Attributes: - parent (str): - Required. The name of the agent to update or create intents - 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://". - intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): - The collection of intents 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. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - intent_batch_uri = proto.Field( - proto.STRING, - number=2, - oneof='intent_batch', - ) - intent_batch_inline = proto.Field( - proto.MESSAGE, - number=3, - oneof='intent_batch', - message='IntentBatch', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - intent_view = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent]): - The collection of updated or created intents. - """ - - intents = 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 (Sequence[google.cloud.dialogflow_v2.types.Intent]): - Required. The collection of intents to delete. Only intent - ``name`` must be filled in. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - intents = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent', - ) - - -class IntentBatch(proto.Message): - r"""This message is a wrapper around a collection of intents. - Attributes: - intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): - A collection of intents. - """ - - intents = 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 e66b99a29..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py +++ /dev/null @@ -1,225 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - '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 = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesRequest(proto.Message): - 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListKnowledgeBasesResponse(proto.Message): - r"""Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - knowledge_bases (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - knowledge_base = 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 = proto.Field( - proto.STRING, - number=1, - ) - force = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - update_mask = 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 85e2f148a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py +++ /dev/null @@ -1,836 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import 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', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'OutputAudio', - 'AutomatedAgentReply', - 'ArticleAnswer', - 'FaqAnswer', - 'SuggestionResult', - 'AnnotatedMessagePart', - 'MessageAnnotation', - }, -) - - -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. - """ - class Role(proto.Enum): - r"""Enumeration of the roles a participant can play in a - conversation. - """ - ROLE_UNSPECIFIED = 0 - HUMAN_AGENT = 1 - AUTOMATED_AGENT = 2 - END_USER = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - role = proto.Field( - proto.ENUM, - number=2, - enum=Role, - ) - sip_recording_media_label = proto.Field( - proto.STRING, - number=6, - ) - - -class Message(proto.Message): - r"""Represents a message posted into a conversation. - Attributes: - name (str): - 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. - message_annotation (google.cloud.dialogflow_v2.types.MessageAnnotation): - Output only. The annotation for the message. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - content = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - participant = proto.Field( - proto.STRING, - number=4, - ) - participant_role = proto.Field( - proto.ENUM, - number=5, - enum='Participant.Role', - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - message_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='MessageAnnotation', - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListParticipantsResponse(proto.Message): - r"""The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - Attributes: - participants (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Participant', - ) - next_page_token = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Participant', - ) - update_mask = 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]. - - 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. - event_input (google.cloud.dialogflow_v2.types.EventInput): - An input event to send to Dialogflow. - 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. - 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 = proto.Field( - proto.STRING, - number=1, - ) - text_input = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message=session.TextInput, - ) - event_input = proto.Field( - proto.MESSAGE, - number=8, - oneof='input', - message=session.EventInput, - ) - reply_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=audio_config.OutputAudioConfig, - ) - query_params = proto.Field( - proto.MESSAGE, - number=9, - message=session.QueryParameters, - ) - request_id = proto.Field( - proto.STRING, - number=11, - ) - - -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 = 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 (Sequence[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 (Sequence[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. - """ - - reply_text = proto.Field( - proto.STRING, - number=1, - ) - reply_audio = proto.Field( - proto.MESSAGE, - number=2, - message='OutputAudio', - ) - automated_agent_reply = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentReply', - ) - message = proto.Field( - proto.MESSAGE, - number=5, - message='Message', - ) - human_agent_suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='SuggestionResult', - ) - end_user_suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - dtmf_parameters = proto.Field( - proto.MESSAGE, - number=9, - message='DtmfParameters', - ) - - -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): - 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][google.cloud.dialogflow.v2.SuggestArticlesRequest.latest_message] - to use as context when compiling the suggestion. By default - 20 and at most 50. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestArticlesResponse(proto.Message): - r"""The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - Attributes: - article_answers (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ArticleAnswer', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = 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): - 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 = proto.Field( - proto.STRING, - number=1, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestFaqAnswersResponse(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - Attributes: - faq_answers (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FaqAnswer', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = 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 = proto.Field( - proto.MESSAGE, - number=1, - message=audio_config.OutputAudioConfig, - ) - audio = proto.Field( - proto.BYTES, - number=2, - ) - - -class AutomatedAgentReply(proto.Message): - r"""Represents a response from an automated agent. - Attributes: - detect_intent_response (google.cloud.dialogflow_v2.types.DetectIntentResponse): - Response of the Dialogflow - [Sessions.DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] - call. - """ - - detect_intent_response = proto.Field( - proto.MESSAGE, - number=1, - message=session.DetectIntentResponse, - ) - - -class ArticleAnswer(proto.Message): - r"""Represents article answer. - Attributes: - title (str): - The article title. - uri (str): - The article URI. - snippets (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.ArticleAnswer.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - snippets = proto.RepeatedField( - proto.STRING, - number=3, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - -class FaqAnswer(proto.Message): - r"""Represents answer from "frequently asked questions". - Attributes: - answer (str): - The piece of text from the ``source`` knowledge base - 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 (Sequence[google.cloud.dialogflow_v2.types.FaqAnswer.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - question = proto.Field( - proto.STRING, - number=3, - ) - source = proto.Field( - proto.STRING, - number=4, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - -class SuggestionResult(proto.Message): - 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]. - - Attributes: - error (google.rpc.status_pb2.Status): - Error status if the request failed. - suggest_articles_response (google.cloud.dialogflow_v2.types.SuggestArticlesResponse): - SuggestArticlesResponse if request is for - ARTICLE_SUGGESTION. - suggest_faq_answers_response (google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse): - SuggestFaqAnswersResponse if request is for FAQ_ANSWER. - """ - - error = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion_response', - message=status_pb2.Status, - ) - suggest_articles_response = proto.Field( - proto.MESSAGE, - number=2, - oneof='suggestion_response', - message='SuggestArticlesResponse', - ) - suggest_faq_answers_response = proto.Field( - proto.MESSAGE, - number=3, - oneof='suggestion_response', - message='SuggestFaqAnswersResponse', - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - formatted_value = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - - -class MessageAnnotation(proto.Message): - r"""Represents the result of annotation for the message. - Attributes: - parts (Sequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): - The collection of annotated message parts ordered by their - 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnnotatedMessagePart', - ) - contain_entities = proto.Field( - proto.BOOL, - number=2, - ) - - -__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 37e736830..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py +++ /dev/null @@ -1,964 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio = proto.Field( - proto.BYTES, - number=5, - ) - - -class DetectIntentResponse(proto.Message): - r"""The message returned from the DetectIntent method. - Attributes: - response_id (str): - The unique identifier of the response. It can - 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 = proto.Field( - proto.STRING, - number=1, - ) - query_result = proto.Field( - proto.MESSAGE, - number=2, - message='QueryResult', - ) - webhook_status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - output_audio = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config = 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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2.types.QueryParameters.WebhookHeadersEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - geo_location = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - contexts = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=context.Context, - ) - reset_contexts = proto.Field( - proto.BOOL, - number=4, - ) - session_entity_types = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) - payload = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - sentiment_analysis_request_config = proto.Field( - proto.MESSAGE, - number=10, - message='SentimentAnalysisRequestConfig', - ) - webhook_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - - -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. - - Attributes: - audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - text (google.cloud.dialogflow_v2.types.TextInput): - The natural language text to be processed. - event (google.cloud.dialogflow_v2.types.EventInput): - The event to be processed. - """ - - audio_config = proto.Field( - proto.MESSAGE, - number=1, - oneof='input', - message=gcd_audio_config.InputAudioConfig, - ) - text = proto.Field( - proto.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - event = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='EventInput', - ) - - -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. - 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 (Sequence[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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=15, - ) - speech_recognition_confidence = proto.Field( - proto.FLOAT, - number=2, - ) - action = proto.Field( - proto.STRING, - number=3, - ) - parameters = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - all_required_params_present = proto.Field( - proto.BOOL, - number=5, - ) - fulfillment_text = proto.Field( - proto.STRING, - number=6, - ) - fulfillment_messages = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) - webhook_source = proto.Field( - proto.STRING, - number=8, - ) - webhook_payload = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=context.Context, - ) - intent = proto.Field( - proto.MESSAGE, - number=11, - message=gcd_intent.Intent, - ) - intent_detection_confidence = proto.Field( - proto.FLOAT, - number=12, - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=14, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = 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 = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - single_utterance = proto.Field( - proto.BOOL, - number=4, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio = 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 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. 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 = proto.Field( - proto.STRING, - number=1, - ) - recognition_result = proto.Field( - proto.MESSAGE, - number=2, - message='StreamingRecognitionResult', - ) - query_result = proto.Field( - proto.MESSAGE, - number=3, - message='QueryResult', - ) - webhook_status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - output_audio = proto.Field( - proto.BYTES, - number=5, - ) - output_audio_config = 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. - - Example: - - 1. transcript: "tube" - - 2. transcript: "to be a" - - 3. transcript: "to be" - - 4. transcript: "to be or not to be" is_final: true - - 5. transcript: " that's" - - 6. transcript: " that is" - - 7. message_type: ``END_OF_SINGLE_UTTERANCE`` - - 8. transcript: " that is the question" is_final: true - - Only two of the responses contain final results (#4 and #8 indicated - by ``is_final: true``). Concatenating these generates the full - transcript: "to be or not to be that is the question". - - In each response we populate: - - - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. - - - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. - - 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 (Sequence[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``. - """ - class MessageType(proto.Enum): - r"""Type of the response message.""" - MESSAGE_TYPE_UNSPECIFIED = 0 - TRANSCRIPT = 1 - END_OF_SINGLE_UTTERANCE = 2 - - message_type = proto.Field( - proto.ENUM, - number=1, - enum=MessageType, - ) - transcript = proto.Field( - proto.STRING, - number=2, - ) - is_final = proto.Field( - proto.BOOL, - number=3, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - speech_word_info = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) - speech_end_offset = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class TextInput(proto.Message): - r"""Represents the natural language text to be processed. - Attributes: - text (str): - Required. The UTF-8 encoded natural language - text to be processed. Text length must not - exceed 256 characters. - 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class SentimentAnalysisRequestConfig(proto.Message): - r"""Configures the types of sentiment analysis to perform. - Attributes: - analyze_query_text_sentiment (bool): - Instructs the service to perform sentiment analysis on - ``query_text``. If not provided, sentiment analysis is not - performed on ``query_text``. - """ - - analyze_query_text_sentiment = 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 = 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. - - 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 = proto.Field( - proto.FLOAT, - number=1, - ) - magnitude = 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 6924dfd26..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py +++ /dev/null @@ -1,251 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 (Sequence[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.""" - ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 - ENTITY_OVERRIDE_MODE_OVERRIDE = 1 - ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - entity_override_mode = proto.Field( - proto.ENUM, - number=2, - enum=EntityOverrideMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=entity_type.EntityType.Entity, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - session_entity_type = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - update_mask = 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 = 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 ff4f05e76..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py +++ /dev/null @@ -1,93 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__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 (Sequence[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 messsage. - """ - class Severity(proto.Enum): - r"""Represents a level of severity.""" - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - CRITICAL = 4 - - severity = proto.Field( - proto.ENUM, - number=1, - enum=Severity, - ) - entries = proto.RepeatedField( - proto.STRING, - number=3, - ) - error_message = proto.Field( - proto.STRING, - number=4, - ) - - -class ValidationResult(proto.Message): - r"""Represents the output of agent validation. - Attributes: - validation_errors (Sequence[google.cloud.dialogflow_v2.types.ValidationError]): - Contains all validation errors. - """ - - validation_errors = 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/webhook.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py deleted file mode 100644 index cbbb1af87..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py +++ /dev/null @@ -1,230 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 = proto.Field( - proto.STRING, - number=4, - ) - response_id = proto.Field( - proto.STRING, - number=1, - ) - query_result = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_session.QueryResult, - ) - original_detect_intent_request = proto.Field( - proto.MESSAGE, - number=3, - message='OriginalDetectIntentRequest', - ) - - -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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - fulfillment_messages = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=intent.Intent.Message, - ) - source = proto.Field( - proto.STRING, - number=3, - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=context.Context, - ) - followup_event_input = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_session.EventInput, - ) - session_entity_types = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=session_entity_type.SessionEntityType, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - payload = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b4854..000000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index 3b2c9dcdd..000000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/dialogflow_v2/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 cc0f68eb9..000000000 --- a/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py +++ /dev/null @@ -1,257 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_environment': ('parent', 'environment', 'environment_id', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'create_version': ('parent', 'version', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_environment': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'delete_version': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_environment': ('name', ), - 'get_environment_history': ('parent', 'page_size', 'page_token', ), - 'get_fulfillment': ('name', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'get_version': ('name', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_versions': ('parent', 'page_size', 'page_token', ), - 'reload_document': ('name', 'content_uri', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), - 'update_fulfillment': ('fulfillment', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - 'update_version': ('version', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - 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: not a.keyword.value 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 4601e7528..000000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-dialogflow', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 00c530ea3..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py +++ /dev/null @@ -1,3145 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.agents import AgentsAsyncClient -from google.cloud.dialogflow_v2.services.agents import AgentsClient -from google.cloud.dialogflow_v2.services.agents import pagers -from google.cloud.dialogflow_v2.services.agents import transports -from google.cloud.dialogflow_v2.services.agents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.agents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import agent -from google.cloud.dialogflow_v2.types import agent as gcd_agent -from google.cloud.dialogflow_v2.types import validation_result -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - AgentsClient, - AgentsAsyncClient, -]) -def test_agents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AgentsClient, - AgentsAsyncClient, -]) -def test_agents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_agents_client_get_transport_class(): - transport = AgentsClient.get_transport_class() - available_transports = [ - transports.AgentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): - 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.2552, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - tier=agent.Agent.Tier.TIER_STANDARD, - ) - response = client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -def test_get_agent_from_dict(): - test_get_agent(request_type=dict) - - -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.2552, - 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.2552, 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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): - 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.2552, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - tier=gcd_agent.Agent.Tier.TIER_STANDARD, - ) - response = client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -def test_set_agent_from_dict(): - test_set_agent(request_type=dict) - - -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.2552, - 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.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -@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 = 'agent.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - call.return_value = gcd_agent.Agent() - client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=agent.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 = 'agent.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - 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=agent.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] - assert args[0].agent == gcd_agent.Agent(parent='parent_value') - - -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] - assert args[0].agent == gcd_agent.Agent(parent='parent_value') - - -@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'), - ) - - -def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): - 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_from_dict(): - test_delete_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): - 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_from_dict(): - test_search_agents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) - -def test_search_agents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): - 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_from_dict(): - test_train_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): - 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_from_dict(): - test_export_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): - 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_from_dict(): - test_import_agent(request_type=dict) - - -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'] - - -def test_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): - 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_from_dict(): - test_restore_agent(request_type=dict) - - -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'] - - -def test_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): - 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_from_dict(): - test_get_validation_result(request_type=dict) - - -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'] - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_agents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_agents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_agents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AgentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AgentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_agents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_agents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_agents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_agents_host_no_port(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_agents_host_with_port(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 ef6a2489b..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py +++ /dev/null @@ -1,1661 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsAsyncClient -from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsClient -from google.cloud.dialogflow_v2.services.answer_records import pagers -from google.cloud.dialogflow_v2.services.answer_records import transports -from google.cloud.dialogflow_v2.services.answer_records.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.answer_records.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.cloud.dialogflow_v2.types import participant -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - AnswerRecordsClient, - AnswerRecordsAsyncClient, -]) -def test_answer_records_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AnswerRecordsClient, - AnswerRecordsAsyncClient, -]) -def test_answer_records_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_answer_records_client_get_transport_class(): - transport = AnswerRecordsClient.get_transport_class() - available_transports = [ - transports.AnswerRecordsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): - 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_from_dict(): - test_list_answer_records(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) - -def test_list_answer_records_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_update_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - 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_from_dict(): - test_update_answer_record(request_type=dict) - - -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 = 'answer_record.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=answer_record.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 = 'answer_record.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=answer_record.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] - assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient( - credentials=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']), - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_answer_records_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AnswerRecordsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_answer_records_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AnswerRecordsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_answer_records_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AnswerRecordsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_answer_records_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AnswerRecordsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_answer_records_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_answer_records_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_answer_records_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_answer_records_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_answer_records_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_answer_records_host_no_port(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_answer_records_host_with_port(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 121896027..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py +++ /dev/null @@ -1,2595 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.contexts import ContextsAsyncClient -from google.cloud.dialogflow_v2.services.contexts import ContextsClient -from google.cloud.dialogflow_v2.services.contexts import pagers -from google.cloud.dialogflow_v2.services.contexts import transports -from google.cloud.dialogflow_v2.services.contexts.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.contexts.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - ContextsClient, - ContextsAsyncClient, -]) -def test_contexts_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ContextsClient, - ContextsAsyncClient, -]) -def test_contexts_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_contexts_client_get_transport_class(): - transport = ContextsClient.get_transport_class() - available_transports = [ - transports.ContextsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): - 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_from_dict(): - test_list_contexts(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) - -def test_list_contexts_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): - 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_from_dict(): - test_get_context(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): - 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_from_dict(): - test_create_context(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].context == gcd_context.Context(name='name_value') - - -def test_create_context_flattened_error(): - client = ContextsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].context == gcd_context.Context(name='name_value') - - -@pytest.mark.asyncio -async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient( - credentials=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'), - ) - - -def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): - 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_from_dict(): - test_update_context(request_type=dict) - - -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 = 'context.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_context), - '__call__') as call: - call.return_value = gcd_context.Context() - client.update_context(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=context.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 = 'context.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_context), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) - - # Establish that the underlying gRPC stub method was called. - 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=context.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] - assert args[0].context == gcd_context.Context(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].context == gcd_context.Context(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient( - credentials=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']), - ) - - -def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): - 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_from_dict(): - test_delete_context(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): - 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_from_dict(): - test_delete_all_contexts(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_contexts_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_contexts_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_contexts_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ContextsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_contexts_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ContextsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_contexts_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_contexts_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_contexts_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_contexts_host_no_port(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_contexts_host_with_port(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 64ef56a29..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py +++ /dev/null @@ -1,2458 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.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.services.conversation_profiles.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - ConversationProfilesClient, - ConversationProfilesAsyncClient, -]) -def test_conversation_profiles_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ConversationProfilesClient, - ConversationProfilesAsyncClient, -]) -def test_conversation_profiles_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversation_profiles_client_get_transport_class(): - transport = ConversationProfilesClient.get_transport_class() - available_transports = [ - transports.ConversationProfilesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): - 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_from_dict(): - test_list_conversation_profiles(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) - -def test_list_conversation_profiles_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): - 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', - ) - 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' - - -def test_get_conversation_profile_from_dict(): - test_get_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - 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', - ) - 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' - - -def test_create_conversation_profile_from_dict(): - test_create_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].parent == 'parent_value' - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - - -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] - assert args[0].parent == 'parent_value' - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - - -@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'), - ) - - -def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - 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', - ) - 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' - - -def test_update_conversation_profile_from_dict(): - test_update_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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 = 'conversation_profile.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=conversation_profile.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 = 'conversation_profile.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=conversation_profile.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] - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - credentials=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']), - ) - - -def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): - 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_from_dict(): - test_delete_conversation_profile(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationProfilesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationProfilesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationProfilesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversation_profiles_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversation_profiles_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_conversation_profiles_host_no_port(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversation_profiles_host_with_port(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_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 = ConversationProfilesClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "octopus", - "knowledge_base": "oyster", - "document": "nudibranch", - } - 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 = "cuttlefish" - knowledge_base = "mussel" - 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": "winkle", - "knowledge_base": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationProfilesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationProfilesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = ConversationProfilesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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_withDEFAULT_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) 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 3ddeb0393..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ /dev/null @@ -1,2618 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.conversations import ConversationsAsyncClient -from google.cloud.dialogflow_v2.services.conversations import ConversationsClient -from google.cloud.dialogflow_v2.services.conversations import pagers -from google.cloud.dialogflow_v2.services.conversations import transports -from google.cloud.dialogflow_v2.services.conversations.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.conversations.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2.types import participant -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - ConversationsClient, - ConversationsAsyncClient, -]) -def test_conversations_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ConversationsClient, - ConversationsAsyncClient, -]) -def test_conversations_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversations_client_get_transport_class(): - transport = ConversationsClient.get_transport_class() - available_transports = [ - transports.ConversationsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): - 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_from_dict(): - test_create_conversation(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].conversation == gcd_conversation.Conversation(name='name_value') - - -def test_create_conversation_flattened_error(): - client = ConversationsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].conversation == gcd_conversation.Conversation(name='name_value') - - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - credentials=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'), - ) - - -def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): - 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_from_dict(): - test_list_conversations(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - -def test_list_conversations_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): - 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_from_dict(): - test_get_conversation(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): - 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_from_dict(): - test_complete_conversation(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): - 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_from_dict(): - test_list_messages(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) - -def test_list_messages_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_conversations_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversations_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_conversations_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversations_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_conversations_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_conversations_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_conversations_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversations_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversations_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_conversations_host_no_port(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversations_host_with_port(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_path(): - project = "squid" - conversation = "clam" - 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": "whelk", - "conversation": "octopus", - } - 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 = "oyster" - conversation_profile = "nudibranch" - 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": "cuttlefish", - "conversation_profile": "mussel", - } - 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 = "winkle" - conversation = "nautilus" - message = "scallop" - 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": "abalone", - "conversation": "squid", - "message": "clam", - } - 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 = "whelk" - 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": "octopus", - } - 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 = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - 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 = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - 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 = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ConversationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - 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 = "scallop" - location = "abalone" - 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": "squid", - "location": "clam", - } - 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_withDEFAULT_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) 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 e8c229933..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py +++ /dev/null @@ -1,2655 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.documents import DocumentsAsyncClient -from google.cloud.dialogflow_v2.services.documents import DocumentsClient -from google.cloud.dialogflow_v2.services.documents import pagers -from google.cloud.dialogflow_v2.services.documents import transports -from google.cloud.dialogflow_v2.services.documents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.documents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import document -from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - DocumentsClient, - DocumentsAsyncClient, -]) -def test_documents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - DocumentsClient, - DocumentsAsyncClient, -]) -def test_documents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_documents_client_get_transport_class(): - transport = DocumentsClient.get_transport_class() - available_transports = [ - transports.DocumentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): - 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_from_dict(): - test_list_documents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - -def test_list_documents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): - 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, - 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 - - -def test_get_document_from_dict(): - test_get_document(request_type=dict) - - -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, - )) - 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 - - -@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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): - 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_from_dict(): - test_create_document(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].document == gcd_document.Document(name='name_value') - - -def test_create_document_flattened_error(): - client = DocumentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].document == gcd_document.Document(name='name_value') - - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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'), - ) - - -def test_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): - 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_from_dict(): - test_delete_document(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): - 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_from_dict(): - test_update_document(request_type=dict) - - -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 = 'document.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=document.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 = 'document.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = 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=document.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] - assert args[0].document == gcd_document.Document(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].document == gcd_document.Document(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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']), - ) - - -def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): - 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_from_dict(): - test_reload_document(request_type=dict) - - -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] - assert args[0].name == 'name_value' - 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] - assert args[0].name == 'name_value' - assert args[0].content_uri == 'content_uri_value' - - -@pytest.mark.asyncio -async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - 'delete_document', - 'update_document', - 'reload_document', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_documents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_documents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_documents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_documents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_documents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_documents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_documents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_documents_host_no_port(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_documents_host_with_port(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 5dec00c3b..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py +++ /dev/null @@ -1,3574 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.entity_types import EntityTypesAsyncClient -from google.cloud.dialogflow_v2.services.entity_types import EntityTypesClient -from google.cloud.dialogflow_v2.services.entity_types import pagers -from google.cloud.dialogflow_v2.services.entity_types import transports -from google.cloud.dialogflow_v2.services.entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import entity_type -from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - EntityTypesClient, - EntityTypesAsyncClient, -]) -def test_entity_types_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - EntityTypesClient, - EntityTypesAsyncClient, -]) -def test_entity_types_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_entity_types_client_get_transport_class(): - transport = EntityTypesClient.get_transport_class() - available_transports = [ - transports.EntityTypesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): - 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_from_dict(): - test_list_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) - -def test_list_entity_types_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): - 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_from_dict(): - test_get_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): - 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_from_dict(): - test_create_entity_type(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -def test_create_entity_type_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): - 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_from_dict(): - test_update_entity_type(request_type=dict) - - -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 = 'entity_type.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=entity_type.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 = 'entity_type.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=entity_type.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] - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -def test_update_entity_type_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): - 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_from_dict(): - test_delete_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): - 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_from_dict(): - test_batch_update_entity_types(request_type=dict) - - -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'] - - -def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): - 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_from_dict(): - test_batch_delete_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type_names == ['entity_type_names_value'] - - -def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type_names == ['entity_type_names_value'] - - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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'], - ) - - -def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): - 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_from_dict(): - test_batch_create_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -def test_batch_create_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): - 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_from_dict(): - test_batch_update_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -def test_batch_update_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): - 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_from_dict(): - test_batch_delete_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_values == ['entity_values_value'] - assert args[0].language_code == 'language_code_value' - - -def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_values == ['entity_values_value'] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EntityTypesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EntityTypesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_entity_types_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_entity_types_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_entity_types_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_entity_types_host_no_port(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_entity_types_host_with_port(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 b4f486182..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py +++ /dev/null @@ -1,2420 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.environments import EnvironmentsAsyncClient -from google.cloud.dialogflow_v2.services.environments import EnvironmentsClient -from google.cloud.dialogflow_v2.services.environments import pagers -from google.cloud.dialogflow_v2.services.environments import transports -from google.cloud.dialogflow_v2.services.environments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.environments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import environment -from google.cloud.dialogflow_v2.types import fulfillment -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - EnvironmentsClient, - EnvironmentsAsyncClient, -]) -def test_environments_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - EnvironmentsClient, - EnvironmentsAsyncClient, -]) -def test_environments_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): - 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_from_dict(): - test_list_environments(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -def test_list_environments_flattened_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_environments( - environment.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.ListEnvironmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_environments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_environments_flattened_error_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_environments( - environment.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_pager(): - client = EnvironmentsClient( - credentials=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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) - -def test_list_environments_pages(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): - 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_from_dict(): - test_get_environment(request_type=dict) - - -def test_get_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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'] - - -def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -def test_create_environment_from_dict(): - test_create_environment(request_type=dict) - - -def test_create_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - client.create_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - )) - response = await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -@pytest.mark.asyncio -async def test_create_environment_async_from_dict(): - await test_create_environment_async(request_type=dict) - - -def test_create_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.CreateEnvironmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.CreateEnvironmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -def test_update_environment_from_dict(): - test_update_environment(request_type=dict) - - -def test_update_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - client.update_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - )) - response = await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -@pytest.mark.asyncio -async def test_update_environment_async_from_dict(): - await test_update_environment_async(request_type=dict) - - -def test_update_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.UpdateEnvironmentRequest() - - request.environment.name = 'environment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'environment.name=environment.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.UpdateEnvironmentRequest() - - request.environment.name = 'environment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'environment.name=environment.name/value', - ) in kw['metadata'] - - -def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_environment_from_dict(): - test_delete_environment(request_type=dict) - - -def test_delete_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - client.delete_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_environment_async_from_dict(): - await test_delete_environment_async(request_type=dict) - - -def test_delete_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.DeleteEnvironmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = None - client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.DeleteEnvironmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - ) - response = client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetEnvironmentHistoryPager) - assert response.parent == 'parent_value' - assert response.next_page_token == 'next_page_token_value' - - -def test_get_environment_history_from_dict(): - test_get_environment_history(request_type=dict) - - -def test_get_environment_history_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - client.get_environment_history() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - -@pytest.mark.asyncio -async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - )) - response = await client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) - assert response.parent == 'parent_value' - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_get_environment_history_async_from_dict(): - await test_get_environment_history_async(request_type=dict) - - -def test_get_environment_history_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.GetEnvironmentHistoryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - call.return_value = environment.EnvironmentHistory() - client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_environment_history_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.GetEnvironmentHistoryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) - await client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_get_environment_history_pager(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.get_environment_history(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) - -def test_get_environment_history_pages(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - pages = list(client.get_environment_history(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_get_environment_history_async_pager(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - async_pager = await client.get_environment_history(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in responses) - -@pytest.mark.asyncio -async def test_get_environment_history_async_pages(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.get_environment_history(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EnvironmentsGrpcTransport, - ) - -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_environments', - 'get_environment', - 'create_environment', - 'update_environment', - 'delete_environment', - 'get_environment_history', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_environments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_environments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_environments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_environments_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_environments_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_environments_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_environments_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_environments_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_environments_host_no_port(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_environments_host_with_port(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - 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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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_withDEFAULT_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) 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 972981777..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py +++ /dev/null @@ -1,3088 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.intents import IntentsAsyncClient -from google.cloud.dialogflow_v2.services.intents import IntentsClient -from google.cloud.dialogflow_v2.services.intents import pagers -from google.cloud.dialogflow_v2.services.intents import transports -from google.cloud.dialogflow_v2.services.intents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.intents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import intent -from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - IntentsClient, - IntentsAsyncClient, -]) -def test_intents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - IntentsClient, - IntentsAsyncClient, -]) -def test_intents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_intents_client_get_transport_class(): - transport = IntentsClient.get_transport_class() - available_transports = [ - transports.IntentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): - 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_from_dict(): - test_list_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) - -def test_list_intents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): - 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_from_dict(): - test_get_intent(request_type=dict) - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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', - ) - - -def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): - 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_from_dict(): - test_create_intent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - - -def test_create_intent_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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', - ) - - -def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): - 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_from_dict(): - test_update_intent(request_type=dict) - - -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 = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = gcd_intent.Intent() - client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=intent.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 = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - 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=intent.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] - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@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']), - ) - - -def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): - 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_from_dict(): - test_delete_intent(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): - 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_from_dict(): - test_batch_update_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - - -def test_batch_update_intents_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - 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')]), - ) - - -def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): - 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_from_dict(): - test_batch_delete_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intents == [intent.Intent(name='name_value')] - - -def test_batch_delete_intents_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].intents == [intent.Intent(name='name_value')] - - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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')], - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_intents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_intents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_intents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - IntentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - IntentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_intents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_intents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_intents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_intents_host_no_port(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_intents_host_with_port(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 ebaf0718f..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py +++ /dev/null @@ -1,2378 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.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.services.knowledge_bases.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - KnowledgeBasesClient, - KnowledgeBasesAsyncClient, -]) -def test_knowledge_bases_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - KnowledgeBasesClient, - KnowledgeBasesAsyncClient, -]) -def test_knowledge_bases_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_knowledge_bases_client_get_transport_class(): - transport = KnowledgeBasesClient.get_transport_class() - available_transports = [ - transports.KnowledgeBasesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): - 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_from_dict(): - test_list_knowledge_bases(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) - -def test_list_knowledge_bases_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): - 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_from_dict(): - test_get_knowledge_base(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - 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_from_dict(): - test_create_knowledge_base(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - - -def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - - -@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'), - ) - - -def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - 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_from_dict(): - test_delete_knowledge_base(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - 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_from_dict(): - test_update_knowledge_base(request_type=dict) - - -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 = 'knowledge_base.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=knowledge_base.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 = 'knowledge_base.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=knowledge_base.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] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - credentials=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']), - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KnowledgeBasesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KnowledgeBasesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_knowledge_bases_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_knowledge_bases_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_knowledge_bases_host_no_port(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_knowledge_bases_host_with_port(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 27391136a..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py +++ /dev/null @@ -1,2957 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.participants import ParticipantsAsyncClient -from google.cloud.dialogflow_v2.services.participants import ParticipantsClient -from google.cloud.dialogflow_v2.services.participants import pagers -from google.cloud.dialogflow_v2.services.participants import transports -from google.cloud.dialogflow_v2.services.participants.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.participants.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import entity_type -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.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 - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - ParticipantsClient, - ParticipantsAsyncClient, -]) -def test_participants_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ParticipantsClient, - ParticipantsAsyncClient, -]) -def test_participants_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_participants_client_get_transport_class(): - transport = ParticipantsClient.get_transport_class() - available_transports = [ - transports.ParticipantsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): - 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', - ) - 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' - - -def test_create_participant_from_dict(): - test_create_participant(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].parent == 'parent_value' - assert args[0].participant == gcd_participant.Participant(name='name_value') - - -def test_create_participant_flattened_error(): - client = ParticipantsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].participant == gcd_participant.Participant(name='name_value') - - -@pytest.mark.asyncio -async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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'), - ) - - -def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): - 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', - ) - 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' - - -def test_get_participant_from_dict(): - test_get_participant(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): - 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_from_dict(): - test_list_participants(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) - -def test_list_participants_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_update_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): - 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', - ) - 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' - - -def test_update_participant_from_dict(): - test_update_participant(request_type=dict) - - -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', - )) - 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' - - -@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 = 'participant.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=participant.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 = 'participant.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=participant.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] - assert args[0].participant == gcd_participant.Participant(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].participant == gcd_participant.Participant(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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']), - ) - - -def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): - 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_from_dict(): - test_analyze_content(request_type=dict) - - -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] - assert args[0].participant == 'participant_value' - assert args[0].event_input == session.EventInput(name='name_value') - - -def test_analyze_content_flattened_error(): - client = ParticipantsClient( - credentials=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] - assert args[0].participant == 'participant_value' - assert args[0].event_input == session.EventInput(name='name_value') - - -@pytest.mark.asyncio -async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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'), - ) - - -def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): - 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_from_dict(): - test_suggest_articles(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): - 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_from_dict(): - test_suggest_faq_answers(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - 'suggest_articles', - 'suggest_faq_answers', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_participants_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_participants_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParticipantsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_participants_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParticipantsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_participants_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParticipantsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_participants_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_participants_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_participants_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_participants_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_participants_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_participants_host_no_port(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_participants_host_with_port(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - 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": "octopus", - "session": "oyster", - "context": "nudibranch", - } - 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 = "cuttlefish" - intent = "mussel" - 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": "winkle", - "intent": "nautilus", - } - 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 = "scallop" - conversation = "abalone" - message = "squid" - 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": "clam", - "conversation": "whelk", - "message": "octopus", - } - 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 = "oyster" - conversation = "nudibranch" - participant = "cuttlefish" - 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": "mussel", - "conversation": "winkle", - "participant": "nautilus", - } - 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 = "scallop" - session = "abalone" - entity_type = "squid" - 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": "clam", - "session": "whelk", - "entity_type": "octopus", - } - 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 = "oyster" - 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": "nudibranch", - } - 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 = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ParticipantsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - 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 = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ParticipantsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - 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 = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ParticipantsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - 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 = "squid" - location = "clam" - 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": "whelk", - "location": "octopus", - } - 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_withDEFAULT_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) 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 9aadedc4f..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py +++ /dev/null @@ -1,2369 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.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.services.session_entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import entity_type -from google.cloud.dialogflow_v2.types import session_entity_type -from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - SessionEntityTypesClient, - SessionEntityTypesAsyncClient, -]) -def test_session_entity_types_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SessionEntityTypesClient, - SessionEntityTypesAsyncClient, -]) -def test_session_entity_types_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_session_entity_types_client_get_transport_class(): - transport = SessionEntityTypesClient.get_transport_class() - available_transports = [ - transports.SessionEntityTypesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): - 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_from_dict(): - test_list_session_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) - -def test_list_session_entity_types_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): - 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_from_dict(): - test_get_session_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - 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_from_dict(): - test_create_session_entity_type(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - - -def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - - -@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'), - ) - - -def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - 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_from_dict(): - test_update_session_entity_type(request_type=dict) - - -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 = 'session_entity_type.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=session_entity_type.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 = 'session_entity_type.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=session_entity_type.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] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - credentials=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']), - ) - - -def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - 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_from_dict(): - test_delete_session_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_session_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionEntityTypesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionEntityTypesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_session_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_session_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_session_entity_types_host_no_port(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_session_entity_types_host_with_port(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 eaea25782..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py +++ /dev/null @@ -1,1381 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.sessions import SessionsAsyncClient -from google.cloud.dialogflow_v2.services.sessions import SessionsClient -from google.cloud.dialogflow_v2.services.sessions import transports -from google.cloud.dialogflow_v2.services.sessions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.sessions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import entity_type -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.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 - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - SessionsClient, - SessionsAsyncClient, -]) -def test_sessions_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SessionsClient, - SessionsAsyncClient, -]) -def test_sessions_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_sessions_client_get_transport_class(): - transport = SessionsClient.get_transport_class() - available_transports = [ - transports.SessionsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): - 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_from_dict(): - test_detect_intent(request_type=dict) - - -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] - assert args[0].session == 'session_value' - assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - - -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] - assert args[0].session == 'session_value' - assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - - -@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)), - ) - - -def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): - 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) - - -def test_streaming_detect_intent_from_dict(): - test_streaming_detect_intent(request_type=dict) - - -@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) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_sessions_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_sessions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_sessions_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_sessions_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_sessions_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_sessions_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_sessions_host_no_port(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_sessions_host_with_port(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 8b2599a7e..000000000 --- a/owl-bot-staging/v2beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-dialogflow" -copyright = u"2020, 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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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/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 f4c430d5a..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Dialogflow v2beta1 API -============================================= - -.. automodule:: google.cloud.dialogflow_v2beta1.types - :members: - :undoc-members: - :show-inheritance: 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 ddb313040..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py +++ /dev/null @@ -1,463 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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 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_event import ConversationEvent -from google.cloud.dialogflow_v2beta1.types.conversation_profile import AutomatedAgentConfig -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 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 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 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 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 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 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', - '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', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - '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', - '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', - 'AutomatedAgentReply', - 'CompileSuggestionRequest', - 'CompileSuggestionResponse', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'ListSuggestionsRequest', - 'ListSuggestionsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'ResponseMessage', - 'SmartReplyAnswer', - '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/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 f2a29bbc0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py +++ /dev/null @@ -1,464 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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_event import ConversationEvent -from .types.conversation_profile import AutomatedAgentConfig -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 UpdateConversationProfileRequest -from .types.document import CreateDocumentRequest -from .types.document import DeleteDocumentRequest -from .types.document import Document -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 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 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 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 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', -'AudioEncoding', -'AutomatedAgentConfig', -'AutomatedAgentReply', -'BatchCreateEntitiesRequest', -'BatchCreateMessagesRequest', -'BatchCreateMessagesResponse', -'BatchDeleteEntitiesRequest', -'BatchDeleteEntityTypesRequest', -'BatchDeleteIntentsRequest', -'BatchUpdateEntitiesRequest', -'BatchUpdateEntityTypesRequest', -'BatchUpdateEntityTypesResponse', -'BatchUpdateIntentsRequest', -'BatchUpdateIntentsResponse', -'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', -'FaqAnswer', -'Fulfillment', -'FulfillmentsClient', -'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', -'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', -'SmartReplyAnswer', -'SpeechContext', -'SpeechModelVariant', -'SpeechToTextConfig', -'SpeechWordInfo', -'SsmlVoiceGender', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SubAgent', -'SuggestArticlesRequest', -'SuggestArticlesResponse', -'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/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/agents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py deleted file mode 100644 index 057c8b80b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 adb33924f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py +++ /dev/null @@ -1,930 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AgentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: agent.GetAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_agent.SetAgentRequest = None, - *, - agent: gcd_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.SetAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: agent.DeleteAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.SearchAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.TrainAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.TrainAgentRequest`): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.ExportAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified agent to a ZIP file. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ExportAgentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: agent.ImportAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ImportAgentRequest`): - The request object. The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.RestoreAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest`): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.GetValidationResultRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest`): - The request object. The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 188371dd7..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py +++ /dev/null @@ -1,1120 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AgentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AgentsTransport): - # transport is a AgentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def get_agent(self, - request: agent.GetAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_agent.SetAgentRequest = None, - *, - agent: gcd_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.SetAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: agent.DeleteAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.SearchAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.TrainAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.TrainAgentRequest): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.ExportAgentRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified agent to a ZIP file. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.ExportAgentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: agent.ImportAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ImportAgentRequest): - The request object. The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.RestoreAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - Args: - request (google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # 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: agent.GetValidationResultRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest): - The request object. The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 cf43dbf95..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 0dc0c06c1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] -_transport_registry['grpc'] = AgentsGrpcTransport -_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport - -__all__ = ( - 'AgentsTransport', - 'AgentsGrpcTransport', - 'AgentsGrpcAsyncIOTransport', -) 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 6c398be5f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py +++ /dev/null @@ -1,305 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import agent -from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent -from google.cloud.dialogflow_v2beta1.types import validation_result -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 90a987a48..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py +++ /dev/null @@ -1,524 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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'] - - -__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 3fa205d80..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,528 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation An operation - which tracks when importing is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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. - - Operation An operation - which tracks when restoring is complete. It only tracks when the - draft agent is updated not when it is done training. - - 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'] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) 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 16c67859b..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 aa8051b2d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py +++ /dev/null @@ -1,457 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.answer_records import pagers -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", - client_options: 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: answer_record.GetAnswerRecordRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> answer_record.AnswerRecord: - r"""Deprecated. - Retrieves a specific answer record. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest`): - The request object. Request message for - [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - 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: answer_record.ListAnswerRecordsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsAsyncPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_answer_record.UpdateAnswerRecordRequest = None, - *, - answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 9db31e2c2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py +++ /dev/null @@ -1,645 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.answer_records import pagers -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AnswerRecordsGrpcTransport -from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AnswerRecordsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AnswerRecordsTransport): - # transport is a AnswerRecordsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def get_answer_record(self, - request: answer_record.GetAnswerRecordRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> answer_record.AnswerRecord: - r"""Deprecated. - Retrieves a specific answer record. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest): - The request object. Request message for - [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - # 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: answer_record.ListAnswerRecordsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_answer_record.UpdateAnswerRecordRequest = None, - *, - answer_record: gcd_answer_record.AnswerRecord = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 edb3335e1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 99c08cf37..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] -_transport_registry['grpc'] = AnswerRecordsGrpcTransport -_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport - -__all__ = ( - 'AnswerRecordsTransport', - 'AnswerRecordsGrpcTransport', - 'AnswerRecordsGrpcAsyncIOTransport', -) 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 52355459d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py +++ /dev/null @@ -1,212 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_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, - ), - } - - @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() - - -__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 12746971d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py +++ /dev/null @@ -1,304 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def get_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'] - - -__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 cc5c09823..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py +++ /dev/null @@ -1,308 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .grpc import AnswerRecordsGrpcTransport - - -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def get_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'] - - -__all__ = ( - 'AnswerRecordsGrpcAsyncIOTransport', -) 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 b0d60f297..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 50269a13b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py +++ /dev/null @@ -1,731 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.contexts import pagers -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ContextsTransport] = "grpc_asyncio", - client_options: 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: context.ListContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsAsyncPager: - r"""Returns the list of all contexts in the specified - session. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListContextsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: context.GetContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_context.CreateContextRequest = None, - *, - parent: str = None, - context: gcd_context.Context = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, - *, - context: gcd_context.Context = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: context.DeleteContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteContextRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: context.DeleteAllContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 768e5b840..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py +++ /dev/null @@ -1,918 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.contexts import pagers -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import field_mask_pb2 # 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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ContextsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ContextsTransport): - # transport is a ContextsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_contexts(self, - request: context.ListContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsPager: - r"""Returns the list of all contexts in the specified - session. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListContextsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: context.GetContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_context.CreateContextRequest = None, - *, - parent: str = None, - context: gcd_context.Context = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_context.UpdateContextRequest = None, - *, - context: gcd_context.Context = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: context.DeleteContextRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteContextRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: context.DeleteAllContextsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 841a02576..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 eb854f545..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] -_transport_registry['grpc'] = ContextsGrpcTransport -_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport - -__all__ = ( - 'ContextsTransport', - 'ContextsGrpcTransport', - 'ContextsGrpcAsyncIOTransport', -) 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 370c9e503..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py +++ /dev/null @@ -1,255 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 1da845890..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py +++ /dev/null @@ -1,384 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 99b6afc78..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py +++ /dev/null @@ -1,388 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'ContextsGrpcAsyncIOTransport', -) 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 3e8e4ea19..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 2e086cd48..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py +++ /dev/null @@ -1,594 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.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.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) - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", - client_options: 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: conversation_profile.ListConversationProfilesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesAsyncPager: - r"""Returns the list of all conversation profiles in the - specified project. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation_profile.GetConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_conversation_profile.CreateConversationProfileRequest = None, - *, - parent: str = None, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, - *, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 9bb545a51..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py +++ /dev/null @@ -1,817 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.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.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 - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationProfilesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationProfilesTransport): - # transport is a ConversationProfilesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_conversation_profiles(self, - request: conversation_profile.ListConversationProfilesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesPager: - r"""Returns the list of all conversation profiles in the - specified project. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation_profile.GetConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_conversation_profile.CreateConversationProfileRequest = None, - *, - parent: str = None, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_conversation_profile.UpdateConversationProfileRequest = None, - *, - conversation_profile: gcd_conversation_profile.ConversationProfile = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: conversation_profile.DeleteConversationProfileRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - Args: - request (google.cloud.dialogflow_v2beta1.types.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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 eb34f0946..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 19a679f49..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] -_transport_registry['grpc'] = ConversationProfilesGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport - -__all__ = ( - 'ConversationProfilesTransport', - 'ConversationProfilesGrpcTransport', - 'ConversationProfilesGrpcAsyncIOTransport', -) 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 7b973512e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 dac1be9b8..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py +++ /dev/null @@ -1,368 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 fdf396093..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py +++ /dev/null @@ -1,372 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'ConversationProfilesGrpcAsyncIOTransport', -) 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 0445da9c4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 04d3afcd9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py +++ /dev/null @@ -1,703 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.conversations import pagers -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 # 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 - - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ConversationsTransport] = "grpc_asyncio", - client_options: 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: gcd_conversation.CreateConversationRequest = None, - *, - parent: str = None, - conversation: gcd_conversation.Conversation = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Returns the list of all conversations in the - specified project. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListConversationsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.GetConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.CompleteConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.BatchCreateMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.BatchCreateMessagesResponse: - r"""Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: conversation.ListMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListMessagesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 82762eb5d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py +++ /dev/null @@ -1,908 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.conversations import pagers -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationsGrpcTransport -from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationsTransport): - # transport is a ConversationsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_conversation(self, - request: gcd_conversation.CreateConversationRequest = None, - *, - parent: str = None, - conversation: gcd_conversation.Conversation = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: conversation.ListConversationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Returns the list of all conversations in the - specified project. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListConversationsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.GetConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.CompleteConversationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.BatchCreateMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.BatchCreateMessagesResponse: - r"""Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: conversation.ListMessagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListMessagesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 589dab410..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py +++ /dev/null @@ -1,263 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 9d9ee9030..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] -_transport_registry['grpc'] = ConversationsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport - -__all__ = ( - 'ConversationsTransport', - 'ConversationsGrpcTransport', - 'ConversationsGrpcAsyncIOTransport', -) 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 3ae1558da..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py +++ /dev/null @@ -1,254 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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, - ), - } - - @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() - - -__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 182b3cf23..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py +++ /dev/null @@ -1,409 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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'] - - -__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 b8fbf4386..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py +++ /dev/null @@ -1,413 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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'] - - -__all__ = ( - 'ConversationsGrpcAsyncIOTransport', -) 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 cee70ad81..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 c5e6d4ec6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py +++ /dev/null @@ -1,845 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, DocumentsTransport] = "grpc_asyncio", - client_options: 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: document.ListDocumentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: document.GetDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_document.CreateDocumentRequest = None, - *, - parent: str = None, - document: gcd_document.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: document.ImportDocumentsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest`): - The request object. Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: document.DeleteDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest`): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_document.UpdateDocumentRequest = None, - *, - document: gcd_document.Document = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: document.ReloadDocumentRequest = None, - *, - name: str = None, - gcs_source: gcs.GcsSource = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 b36a4c671..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py +++ /dev/null @@ -1,1033 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentsTransport): - # transport is a DocumentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_documents(self, - request: document.ListDocumentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: document.GetDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_document.CreateDocumentRequest = None, - *, - parent: str = None, - document: gcd_document.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: document.ImportDocumentsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest): - The request object. Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: document.DeleteDocumentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest): - 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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_document.UpdateDocumentRequest = None, - *, - document: gcd_document.Document = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: document.ReloadDocumentRequest = None, - *, - name: str = None, - gcs_source: gcs.GcsSource = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 a5d3edf67..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 f9ae67be5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] -_transport_registry['grpc'] = DocumentsGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport - -__all__ = ( - 'DocumentsTransport', - 'DocumentsGrpcTransport', - 'DocumentsGrpcAsyncIOTransport', -) 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 30922dcac..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py +++ /dev/null @@ -1,275 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import document -from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 3652aecf9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py +++ /dev/null @@ -1,454 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - 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. - - 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'] - - -__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 108aa230c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py +++ /dev/null @@ -1,458 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - 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. - - 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'] - - -__all__ = ( - 'DocumentsGrpcAsyncIOTransport', -) 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 82dfe86fd..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 9e2f38eb8..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py +++ /dev/null @@ -1,1224 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, EntityTypesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: entity_type.ListEntityTypesRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesAsyncPager: - r"""Returns the list of all entity types in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: entity_type.BatchUpdateEntityTypesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple entity types in the specified agent. - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest`): - The request object. The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: entity_type.BatchDeleteEntityTypesRequest = None, - *, - parent: str = None, - entity_type_names: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entity types in the specified agent. Operation - - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates multiple new entities in the specified entity type. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, - *, - parent: str = None, - entity_values: Sequence[str] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entities in the specified entity type. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 4c402786f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py +++ /dev/null @@ -1,1412 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EntityTypesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EntityTypesTransport): - # transport is a EntityTypesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_entity_types(self, - request: entity_type.ListEntityTypesRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesPager: - r"""Returns the list of all entity types in the specified - agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.GetEntityTypeRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcd_entity_type.EntityType = None, - language_code: str = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: entity_type.DeleteEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: entity_type.BatchUpdateEntityTypesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple entity types in the specified agent. - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest): - The request object. The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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: entity_type.BatchDeleteEntityTypesRequest = None, - *, - parent: str = None, - entity_type_names: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entity types in the specified agent. Operation - - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchCreateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates multiple new entities in the specified entity type. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchUpdateEntitiesRequest = None, - *, - parent: str = None, - entities: Sequence[entity_type.EntityType.Entity] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: entity_type.BatchDeleteEntitiesRequest = None, - *, - parent: str = None, - entity_values: Sequence[str] = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entities in the specified entity type. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 c943d32c2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 1a2aa82dc..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] -_transport_registry['grpc'] = EntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport - -__all__ = ( - 'EntityTypesTransport', - 'EntityTypesGrpcTransport', - 'EntityTypesGrpcAsyncIOTransport', -) 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 0068d90ec..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py +++ /dev/null @@ -1,318 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 9765d9e56..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py +++ /dev/null @@ -1,519 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - Operation - - 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. Operation - - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__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 ac880bcf8..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,523 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - Operation - - 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. Operation - - - 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. - - Operation - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) 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 a3ad29ecd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 2591a9bee..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py +++ /dev/null @@ -1,607 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.environments import pagers -from google.cloud.dialogflow_v2beta1.types import environment -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - - -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) - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: environment.ListEnvironmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsAsyncPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = environment.ListEnvironmentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - 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: environment.GetEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest`): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.GetEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_environment(self, - request: environment.CreateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest`): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.CreateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: environment.UpdateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Updates the specified agent environment. - - This method allows you to deploy new agent versions into the - environment. When an environment is pointed to a new agent - version by setting ``environment.agent_version``, the - environment is temporarily set to the ``LOADING`` state. During - that time, the environment keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest`): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - request = environment.UpdateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment.name", request.environment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest`): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - request = environment.DeleteEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_environment_history(self, - request: environment.GetEnvironmentHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryAsyncPager: - r"""Gets the history of the specified environment. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest`): - The request object. The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = environment.GetEnvironmentHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment_history, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GetEnvironmentHistoryAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 91782d01e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py +++ /dev/null @@ -1,808 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.environments import pagers -from google.cloud.dialogflow_v2beta1.types import environment -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_environments(self, - request: environment.ListEnvironmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a environment.ListEnvironmentsRequest. - # 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: environment.GetEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.GetEnvironmentRequest): - request = environment.GetEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_environment(self, - request: environment.CreateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.CreateEnvironmentRequest): - request = environment.CreateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: environment.UpdateEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Updates the specified agent environment. - - This method allows you to deploy new agent versions into the - environment. When an environment is pointed to a new agent - version by setting ``environment.agent_version``, the - environment is temporarily set to the ``LOADING`` state. During - that time, the environment keeps on serving the previous version - of the agent. After the new agent version is done loading, the - environment is set back to the ``RUNNING`` state. You can use - "-" as Environment ID in environment name to update version in - "draft" environment. WARNING: this will negate all recent - changes to draft and can't be undone. You may want to save the - draft to a version before calling this function. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Environment: - You can create multiple versions of your agent and publish them to separate - environments. - - When you edit an agent, you are editing the draft - agent. At any point, you can save the draft agent as - an agent version, which is an immutable snapshot of - your agent. - - When you save the draft agent, it is published to the - default environment. When you create agent versions, - you can publish them to custom environments. You can - create a variety of custom environments for: - - - testing - - development - - production - - etc. - - For more information, see the [versions and - environments - guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.UpdateEnvironmentRequest): - request = environment.UpdateEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment.name", request.environment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.DeleteEnvironmentRequest): - request = environment.DeleteEnvironmentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_environment_history(self, - request: environment.GetEnvironmentHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryPager: - r"""Gets the history of the specified environment. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): - The request object. The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.GetEnvironmentHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.GetEnvironmentHistoryRequest): - request = environment.GetEnvironmentHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_environment_history] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GetEnvironmentHistoryPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 7419e474f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py +++ /dev/null @@ -1,262 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[environment.EnvironmentHistory]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: - for page in self.pages: - yield from page.entries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GetEnvironmentHistoryAsyncPager: - """A pager for iterating through ``get_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and - provides an ``__aiter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GetEnvironmentHistory`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[environment.EnvironmentHistory]], - request: environment.GetEnvironmentHistoryRequest, - response: environment.EnvironmentHistory, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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) -> AsyncIterable[environment.EnvironmentHistory]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: - async def async_generator(): - async for page in self.pages: - for response in page.entries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/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 fac90efe0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', -) 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 289c1febf..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py +++ /dev/null @@ -1,254 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import environment -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_environments: gapic_v1.method.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.create_environment: gapic_v1.method.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment_history: gapic_v1.method.wrap_method( - self.get_environment_history, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_environments(self) -> 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() - - -__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 848b7e0ac..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,393 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import environment -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 1e54e25c4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,397 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import environment -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) 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 8204500fb..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 6c4a7e568..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py +++ /dev/null @@ -1,889 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, IntentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: intent.ListIntentsRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsAsyncPager: - r"""Returns the list of all intents in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListIntentsRequest`): - 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``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcd_intent.Intent = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, - *, - intent: gcd_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: intent.DeleteIntentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or - indirect followup intents. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: intent.BatchUpdateIntentsRequest = None, - *, - parent: str = None, - intent_batch_uri: str = None, - intent_batch_inline: intent.IntentBatch = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple intents in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, - *, - parent: str = None, - intents: Sequence[intent.Intent] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes intents in the specified agent. - - Operation - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest`): - 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:`Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 ff9aed2ae..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py +++ /dev/null @@ -1,1085 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, IntentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, IntentsTransport): - # transport is a IntentsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_intents(self, - request: intent.ListIntentsRequest = None, - *, - parent: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsPager: - r"""Returns the list of all intents in the specified - agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListIntentsRequest): - 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``. - - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.GetIntentRequest = None, - *, - name: str = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, 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: gcd_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcd_intent.Intent = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_intent.UpdateIntentRequest = None, - *, - intent: gcd_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - language_code: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: intent.DeleteIntentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or - indirect followup intents. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: intent.BatchUpdateIntentsRequest = None, - *, - parent: str = None, - intent_batch_uri: str = None, - intent_batch_inline: intent.IntentBatch = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple intents in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: intent.BatchDeleteIntentsRequest = None, - *, - parent: str = None, - intents: Sequence[intent.Intent] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes intents in the specified agent. - - Operation - - Args: - request (google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest): - 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 (Sequence[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); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 abacee624..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 aa8039bba..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] -_transport_registry['grpc'] = IntentsGrpcTransport -_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport - -__all__ = ( - 'IntentsTransport', - 'IntentsGrpcTransport', - 'IntentsGrpcAsyncIOTransport', -) 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 2fa4de0b4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py +++ /dev/null @@ -1,276 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import intent -from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 cb885b248..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py +++ /dev/null @@ -1,434 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__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 58980cb8a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py +++ /dev/null @@ -1,438 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - """ - # Sanity 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. - - 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. - - 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. - - 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. - - Operation - - 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. - - Operation - - 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'] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) 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 670d8e66d..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 4788424ac..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py +++ /dev/null @@ -1,615 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers -from google.cloud.dialogflow_v2beta1.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", - client_options: 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: knowledge_base.ListKnowledgeBasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: knowledge_base.GetKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, - *, - parent: str = None, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, - *, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 be6d1d63b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py +++ /dev/null @@ -1,802 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers -from google.cloud.dialogflow_v2beta1.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import KnowledgeBasesGrpcTransport -from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, KnowledgeBasesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, KnowledgeBasesTransport): - # transport is a KnowledgeBasesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_knowledge_bases(self, - request: knowledge_base.ListKnowledgeBasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: knowledge_base.GetKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_knowledge_base.CreateKnowledgeBaseRequest = None, - *, - parent: str = None, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: knowledge_base.DeleteKnowledgeBaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, - *, - knowledge_base: gcd_knowledge_base.KnowledgeBase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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``. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 62df0fda9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 c04ef7c9f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] -_transport_registry['grpc'] = KnowledgeBasesGrpcTransport -_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport - -__all__ = ( - 'KnowledgeBasesTransport', - 'KnowledgeBasesGrpcTransport', - 'KnowledgeBasesGrpcAsyncIOTransport', -) 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 95390162e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 589bc3088..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py +++ /dev/null @@ -1,370 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 00d2ee830..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py +++ /dev/null @@ -1,374 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'KnowledgeBasesGrpcAsyncIOTransport', -) 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 376e9e7d4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 5297b9b08..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ /dev/null @@ -1,1007 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.participants import pagers -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -from google.cloud.dialogflow_v2beta1.types import session -from google.protobuf import field_mask_pb2 # 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 - - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, ParticipantsTransport] = "grpc_asyncio", - client_options: 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: gcd_participant.CreateParticipantRequest = None, - *, - parent: str = None, - participant: gcd_participant.Participant = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.ListParticipantsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsAsyncPager: - r"""Returns the list of all participants in the specified - conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_participant.UpdateParticipantRequest = None, - *, - participant: gcd_participant.Participant = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, - *, - participant: str = None, - text_input: session.TextInput = None, - event_input: session.EventInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest`): - 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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 - - async def suggest_articles(self, - request: participant.SuggestArticlesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.SuggestFaqAnswersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.SuggestSmartRepliesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: participant.ListSuggestionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest`): - The request object. The request message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - - """ - # 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: participant.CompileSuggestionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest`): - The request object. The request message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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]. - - """ - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 f1ad0026b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ /dev/null @@ -1,1235 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.participants import pagers -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -from google.cloud.dialogflow_v2beta1.types import session -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ParticipantsGrpcTransport -from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ParticipantsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> 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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ParticipantsTransport): - # transport is a ParticipantsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_participant(self, - request: gcd_participant.CreateParticipantRequest = None, - *, - parent: str = None, - participant: gcd_participant.Participant = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: participant.GetParticipantRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.ListParticipantsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsPager: - r"""Returns the list of all participants in the specified - conversation. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_participant.UpdateParticipantRequest = None, - *, - participant: gcd_participant.Participant = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: gcd_participant.AnalyzeContentRequest = None, - *, - participant: str = None, - text_input: session.TextInput = None, - event_input: session.EventInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 `__. - - Args: - request (google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest): - 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. - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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 suggest_articles(self, - request: participant.SuggestArticlesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.SuggestFaqAnswersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - Args: - request (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.SuggestSmartRepliesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - Args: - request (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: participant.ListSuggestionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest): - The request object. The request message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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. - - """ - # 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: participant.CompileSuggestionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest): - The request object. The request message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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]. - - """ - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 c5935440b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py +++ /dev/null @@ -1,262 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 e30c79b00..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] -_transport_registry['grpc'] = ParticipantsGrpcTransport -_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport - -__all__ = ( - 'ParticipantsTransport', - 'ParticipantsGrpcTransport', - 'ParticipantsGrpcAsyncIOTransport', -) 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 ae1ce5066..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py +++ /dev/null @@ -1,316 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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, - ), - } - - @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 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() - - -__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 a780256b3..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py +++ /dev/null @@ -1,533 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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 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'] - - -__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 8921c8aaf..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py +++ /dev/null @@ -1,537 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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'] - - -__all__ = ( - 'ParticipantsGrpcAsyncIOTransport', -) 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 fb6678b14..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 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 91bf1d001..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py +++ /dev/null @@ -1,649 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.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.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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: session_entity_type.ListSessionEntityTypesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: session_entity_type.GetSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 8ccd7a69d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py +++ /dev/null @@ -1,836 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.services.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.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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionEntityTypesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SessionEntityTypesTransport): - # transport is a SessionEntityTypesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def list_session_entity_types(self, - request: session_entity_type.ListSessionEntityTypesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: session_entity_type.GetSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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: gcd_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcd_session_entity_type.SessionEntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: session_entity_type.DeleteSessionEntityTypeRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 b74bb17f0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflow_v2beta1.types import 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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 fee526724..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] -_transport_registry['grpc'] = SessionEntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport - -__all__ = ( - 'SessionEntityTypesTransport', - 'SessionEntityTypesGrpcTransport', - 'SessionEntityTypesGrpcAsyncIOTransport', -) 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 617f495ec..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py +++ /dev/null @@ -1,241 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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, - ), - } - - @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() - - -__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 d99649031..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py +++ /dev/null @@ -1,374 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 - - -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - -__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 75f33145b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,378 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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 -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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'] - - -__all__ = ( - 'SessionEntityTypesGrpcAsyncIOTransport', -) 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 92490cc5a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 34b20dfac..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ /dev/null @@ -1,406 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 # 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, SessionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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: gcd_session.DetectIntentRequest = None, - *, - session: str = None, - query_input: gcd_session.QueryInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DetectIntentRequest`): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: AsyncIterator[session.StreamingDetectIntentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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). - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - 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 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. 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 0144f4441..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py +++ /dev/null @@ -1,619 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 # type: ignore -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SessionsGrpcTransport -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """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 (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SessionsTransport): - # transport is a SessionsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def detect_intent(self, - request: gcd_session.DetectIntentRequest = None, - *, - session: str = None, - query_input: gcd_session.QueryInput = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DetectIntentRequest): - 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. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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: Iterator[session.StreamingDetectIntentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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). - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - 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 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. 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflow", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "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 fde19f616..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] -_transport_registry['grpc'] = SessionsGrpcTransport -_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport - -__all__ = ( - 'SessionsTransport', - 'SessionsGrpcTransport', - 'SessionsGrpcAsyncIOTransport', -) 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 9a1bbb47f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py +++ /dev/null @@ -1,204 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore - -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflow', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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, - ), - } - - @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() - - -__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 3f18af46f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py +++ /dev/null @@ -1,292 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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. - - 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). - - 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'] - - -__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 c3d48649c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,296 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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. - - 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). - - 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'] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) 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 9354cebac..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py +++ /dev/null @@ -1,444 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ( - 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, -) -from .conversation_event import ( - ConversationEvent, -) -from .conversation_profile import ( - AutomatedAgentConfig, - ConversationProfile, - CreateConversationProfileRequest, - DeleteConversationProfileRequest, - GetConversationProfileRequest, - HumanAgentAssistantConfig, - HumanAgentHandoffConfig, - ListConversationProfilesRequest, - ListConversationProfilesResponse, - LoggingConfig, - NotificationConfig, - UpdateConversationProfileRequest, -) -from .document import ( - CreateDocumentRequest, - DeleteDocumentRequest, - Document, - 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 ( - 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, - AutomatedAgentReply, - CompileSuggestionRequest, - CompileSuggestionResponse, - CreateParticipantRequest, - DtmfParameters, - FaqAnswer, - GetParticipantRequest, - ListParticipantsRequest, - ListParticipantsResponse, - ListSuggestionsRequest, - ListSuggestionsResponse, - Message, - MessageAnnotation, - OutputAudio, - Participant, - ResponseMessage, - SmartReplyAnswer, - 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', - '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', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - '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', - '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', - 'AutomatedAgentReply', - 'CompileSuggestionRequest', - 'CompileSuggestionResponse', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'ListSuggestionsRequest', - 'ListSuggestionsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'ResponseMessage', - 'SmartReplyAnswer', - '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 6d2a1c5ee..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py +++ /dev/null @@ -1,492 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - '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 (Sequence[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. - """ - MATCH_MODE_UNSPECIFIED = 0 - MATCH_MODE_HYBRID = 1 - MATCH_MODE_ML_ONLY = 2 - - class ApiVersion(proto.Enum): - r"""API version for the agent.""" - 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.""" - TIER_UNSPECIFIED = 0 - TIER_STANDARD = 1 - TIER_ENTERPRISE = 2 - TIER_ENTERPRISE_PLUS = 3 - - parent = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - default_language_code = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri = proto.Field( - proto.STRING, - number=7, - ) - enable_logging = proto.Field( - proto.BOOL, - number=8, - ) - match_mode = proto.Field( - proto.ENUM, - number=9, - enum=MatchMode, - ) - classification_threshold = proto.Field( - proto.FLOAT, - number=10, - ) - api_version = proto.Field( - proto.ENUM, - number=14, - enum=ApiVersion, - ) - tier = proto.Field( - proto.ENUM, - number=15, - enum=Tier, - ) - - -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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Agent', - ) - update_mask = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - environment = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchAgentsResponse(proto.Message): - r"""The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - Attributes: - agents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Agent', - ) - next_page_token = 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 = 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - - 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``. - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - agent_uri = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class ImportAgentRequest(proto.Message): - r"""The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - - 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://". - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - - 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://". - agent_content (bytes): - Zip compressed raw byte content for agent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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 80dc99675..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py +++ /dev/null @@ -1,392 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - answer_feedback = proto.Field( - proto.MESSAGE, - number=3, - message='AnswerFeedback', - ) - agent_assistant_record = proto.Field( - proto.MESSAGE, - number=4, - oneof='record', - message='AgentAssistantRecord', - ) - - -class AgentAssistantRecord(proto.Message): - r"""Represents a record of a human agent assistant answer. - Attributes: - article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): - Output only. The article suggestion answer. - faq_answer (google.cloud.dialogflow_v2beta1.types.FaqAnswer): - Output only. The FAQ answer. - """ - - article_suggestion_answer = proto.Field( - proto.MESSAGE, - number=5, - oneof='answer', - message=participant.ArticleAnswer, - ) - faq_answer = proto.Field( - proto.MESSAGE, - number=6, - oneof='answer', - message=participant.FaqAnswer, - ) - - -class AnswerFeedback(proto.Message): - r"""Represents feedback the customer has about the quality & - correctness of a certain answer in a conversation. - - 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. - 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.""" - CORRECTNESS_LEVEL_UNSPECIFIED = 0 - NOT_CORRECT = 1 - PARTIALLY_CORRECT = 2 - FULLY_CORRECT = 3 - - correctness_level = proto.Field( - proto.ENUM, - number=1, - enum=CorrectnessLevel, - ) - agent_assistant_detail_feedback = proto.Field( - proto.MESSAGE, - number=2, - oneof='detail_feedback', - message='AgentAssistantFeedback', - ) - clicked = proto.Field( - proto.BOOL, - number=3, - ) - click_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - displayed = proto.Field( - proto.BOOL, - number=4, - ) - display_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class AgentAssistantFeedback(proto.Message): - r"""Detail feedback of Agent Assistant result. - Attributes: - answer_relevance (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.AnswerRelevance): - Optional. Whether or not the suggested answer is relevant. - - 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.""" - ANSWER_RELEVANCE_UNSPECIFIED = 0 - IRRELEVANT = 1 - RELEVANT = 2 - - class DocumentCorrectness(proto.Enum): - r"""Correctness of document.""" - DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 - INCORRECT = 1 - CORRECT = 2 - - class DocumentEfficiency(proto.Enum): - r"""Efficiency of document.""" - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - submit_timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - summary_text = proto.Field( - proto.STRING, - number=3, - ) - - answer_relevance = proto.Field( - proto.ENUM, - number=1, - enum=AnswerRelevance, - ) - document_correctness = proto.Field( - proto.ENUM, - number=2, - enum=DocumentCorrectness, - ) - document_efficiency = proto.Field( - proto.ENUM, - number=3, - enum=DocumentEfficiency, - ) - summarization_feedback = proto.Field( - proto.MESSAGE, - number=4, - message=SummarizationFeedback, - ) - - -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 = 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/``. - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnswerRecordsResponse(proto.Message): - r"""Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - Attributes: - answer_records (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - next_page_token = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - update_mask = 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 c020068e9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ /dev/null @@ -1,507 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - 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. - """ - 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. - """ - 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 `__. - """ - 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.""" - 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. - """ - 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 (Sequence[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 = proto.RepeatedField( - proto.STRING, - number=1, - ) - boost = proto.Field( - proto.FLOAT, - number=2, - ) - - -class SpeechWordInfo(proto.Message): - r"""Information for a word recognized by the speech recognizer. - Attributes: - word (str): - The word this info is for. - 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 = proto.Field( - proto.STRING, - number=3, - ) - start_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - -class InputAudioConfig(proto.Message): - 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 (Sequence[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 (Sequence[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. - """ - - audio_encoding = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - enable_word_info = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints = proto.RepeatedField( - proto.STRING, - number=4, - ) - speech_contexts = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechContext', - ) - model = proto.Field( - proto.STRING, - number=7, - ) - model_variant = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance = proto.Field( - proto.BOOL, - number=8, - ) - disable_no_speech_recognized_event = proto.Field( - proto.BOOL, - number=14, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - ssml_gender = proto.Field( - proto.ENUM, - number=2, - enum='SsmlVoiceGender', - ) - - -class SynthesizeSpeechConfig(proto.Message): - r"""Configuration of how speech should be synthesized. - Attributes: - speaking_rate (float): - Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 - 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 (Sequence[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 = proto.Field( - proto.DOUBLE, - number=1, - ) - pitch = proto.Field( - proto.DOUBLE, - number=2, - ) - volume_gain_db = proto.Field( - proto.DOUBLE, - number=3, - ) - effects_profile_id = proto.RepeatedField( - proto.STRING, - number=5, - ) - voice = proto.Field( - proto.MESSAGE, - number=4, - message='VoiceSelectionParams', - ) - - -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 = proto.Field( - proto.ENUM, - number=1, - enum='OutputAudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - synthesize_speech_config = proto.Field( - proto.MESSAGE, - number=3, - message='SynthesizeSpeechConfig', - ) - - -class TelephonyDtmfEvents(proto.Message): - r"""A wrapper of repeated TelephonyDtmf digits. - Attributes: - dtmf_events (Sequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): - A sequence of TelephonyDtmf digits. - """ - - dtmf_events = 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): - Optional. 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. - """ - - speech_model_variant = proto.Field( - proto.ENUM, - number=1, - enum='SpeechModelVariant', - ) - - -__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 a2943b2dd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py +++ /dev/null @@ -1,327 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import 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 = proto.Field( - proto.STRING, - number=1, - ) - lifespan_count = proto.Field( - proto.INT32, - number=2, - ) - parameters = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -class ListContextsRequest(proto.Message): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListContextsResponse(proto.Message): - r"""The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - Attributes: - contexts (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Context', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Context', - ) - update_mask = 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 = 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 = 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 39b5ebd47..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py +++ /dev/null @@ -1,462 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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', - }, -) - - -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.""" - 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 - """ - CONVERSATION_STAGE_UNSPECIFIED = 0 - VIRTUAL_AGENT_STAGE = 1 - HUMAN_ASSIST_STAGE = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - lifecycle_state = proto.Field( - proto.ENUM, - number=2, - enum=LifecycleState, - ) - conversation_profile = proto.Field( - proto.STRING, - number=3, - ) - phone_number = proto.Field( - proto.MESSAGE, - number=4, - message='ConversationPhoneNumber', - ) - conversation_stage = proto.Field( - proto.ENUM, - number=7, - enum=ConversationStage, - ) - start_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - conversation = proto.Field( - proto.MESSAGE, - number=2, - message='Conversation', - ) - conversation_id = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListConversationsResponse(proto.Message): - r"""The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - Attributes: - conversations (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Conversation', - ) - next_page_token = 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 = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - requests = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateMessageRequest', - ) - - -class BatchCreateMessagesResponse(proto.Message): - r"""The request message for - [Conversations.BatchCreateMessagesResponse][]. - - Attributes: - messages (Sequence[google.cloud.dialogflow_v2beta1.types.Message]): - Messages created. - """ - - messages = 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 = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListMessagesResponse(proto.Message): - r"""The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - Attributes: - messages (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=participant.Message, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__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 476880977..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py +++ /dev/null @@ -1,78 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - - 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. - """ - class Type(proto.Enum): - r"""Enumeration of the types of events available.""" - TYPE_UNSPECIFIED = 0 - CONVERSATION_STARTED = 1 - CONVERSATION_FINISHED = 2 - NEW_MESSAGE = 5 - UNRECOVERABLE_ERROR = 4 - - conversation = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - error_status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - new_message_payload = 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 a3f7b6eec..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py +++ /dev/null @@ -1,818 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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', - }, -) - - -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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - automated_agent_config = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentConfig', - ) - human_agent_assistant_config = proto.Field( - proto.MESSAGE, - number=4, - message='HumanAgentAssistantConfig', - ) - human_agent_handoff_config = proto.Field( - proto.MESSAGE, - number=5, - message='HumanAgentHandoffConfig', - ) - notification_config = proto.Field( - proto.MESSAGE, - number=6, - message='NotificationConfig', - ) - logging_config = proto.Field( - proto.MESSAGE, - number=7, - message='LoggingConfig', - ) - new_message_event_notification_config = proto.Field( - proto.MESSAGE, - number=8, - message='NotificationConfig', - ) - stt_config = proto.Field( - proto.MESSAGE, - number=9, - message=audio_config.SpeechToTextConfig, - ) - language_code = proto.Field( - proto.STRING, - number=10, - ) - - -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 = 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 = proto.Field( - proto.BOOL, - number=1, - ) - only_end_user = proto.Field( - proto.BOOL, - number=2, - ) - - class SuggestionFeatureConfig(proto.Message): - r"""Config for suggestion features. - Attributes: - suggestion_feature (google.cloud.dialogflow_v2beta1.types.SuggestionFeature): - The suggestion feature. - 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. - """ - - suggestion_feature = proto.Field( - proto.MESSAGE, - number=5, - message=participant.SuggestionFeature, - ) - enable_event_based_suggestion = proto.Field( - proto.BOOL, - number=3, - ) - suggestion_trigger_settings = proto.Field( - proto.MESSAGE, - number=10, - message='HumanAgentAssistantConfig.SuggestionTriggerSettings', - ) - query_config = proto.Field( - proto.MESSAGE, - number=6, - message='HumanAgentAssistantConfig.SuggestionQueryConfig', - ) - conversation_model_config = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.ConversationModelConfig', - ) - - class SuggestionConfig(proto.Message): - r"""Detail human agent assistant config. - Attributes: - feature_configs (Sequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): - Configuration of different suggestion - 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 = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - group_suggestion_responses = proto.Field( - proto.BOOL, - number=3, - ) - - class SuggestionQueryConfig(proto.Message): - r"""Config for suggestion query. - Attributes: - knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): - Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, - FAQ. - document_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): - Query from knowledge base document. It is used by: - SMART_REPLY, SMART_COMPOSE. - dialogflow_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): - Query from Dialogflow agent. It is used by - DIALOGFLOW_ASSIST. - 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 (Sequence[str]): - Required. Knowledge bases to query. Format: - ``projects//locations//knowledgeBases/``. - Currently, only one knowledge base is supported. - """ - - knowledge_bases = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DocumentQuerySource(proto.Message): - r"""Document source settings. - - Supported features: SMART_REPLY, SMART_COMPOSE. - - Attributes: - documents (Sequence[str]): - Required. Knowledge documents to query from. Format: - ``projects//locations//knowledgeBases//documents/``. - Currently, only one document is supported. - """ - - documents = 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 = 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 = proto.Field( - proto.BOOL, - number=1, - ) - drop_virtual_agent_messages = proto.Field( - proto.BOOL, - number=2, - ) - drop_ivr_messages = proto.Field( - proto.BOOL, - number=3, - ) - - knowledge_base_query_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', - ) - document_query_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', - ) - dialogflow_query_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', - ) - max_results = proto.Field( - proto.INT32, - number=4, - ) - confidence_threshold = proto.Field( - proto.FLOAT, - number=5, - ) - context_filter_settings = 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. - - Attributes: - model (str): - Conversation model resource name. Format: - ``projects//conversationModels/``. - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - 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 = proto.Field( - proto.BOOL, - number=2, - ) - enable_sentiment_analysis = proto.Field( - proto.BOOL, - number=3, - ) - - notification_config = proto.Field( - proto.MESSAGE, - number=2, - message='NotificationConfig', - ) - human_agent_suggestion_config = proto.Field( - proto.MESSAGE, - number=3, - message=SuggestionConfig, - ) - end_user_suggestion_config = proto.Field( - proto.MESSAGE, - number=4, - message=SuggestionConfig, - ) - message_analysis_config = proto.Field( - proto.MESSAGE, - number=5, - message=MessageAnalysisConfig, - ) - - -class HumanAgentHandoffConfig(proto.Message): - r"""Defines the hand off to a live agent, typically on which - external agent service provider to connect to a conversation. - Currently, this feature is not general available, please contact - Google to get access. - - Attributes: - live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): - Uses LivePerson (https://www.liveperson.com). - salesforce_live_agent_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): - Uses Salesforce Live Agent. - """ - - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - deployment_id = proto.Field( - proto.STRING, - number=2, - ) - button_id = proto.Field( - proto.STRING, - number=3, - ) - endpoint_domain = proto.Field( - proto.STRING, - number=4, - ) - - live_person_config = proto.Field( - proto.MESSAGE, - number=1, - oneof='agent_service', - message=LivePersonConfig, - ) - salesforce_live_agent_config = proto.Field( - proto.MESSAGE, - number=2, - 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. - - Notification works for phone calls, if this topic either 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. - - 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.""" - MESSAGE_FORMAT_UNSPECIFIED = 0 - PROTO = 1 - JSON = 2 - - topic = proto.Field( - proto.STRING, - number=1, - ) - message_format = proto.Field( - proto.ENUM, - number=2, - enum=MessageFormat, - ) - - -class LoggingConfig(proto.Message): - r"""Defines logging behavior for conversation lifecycle events. - Attributes: - enable_stackdriver_logging (bool): - Whether to log conversation events like - [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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationProfilesResponse(proto.Message): - r"""The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - Attributes: - conversation_profiles (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - conversation_profile = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - update_mask = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -__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 c95fcdfef..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py +++ /dev/null @@ -1,525 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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', - '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``. - - 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 (Sequence[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. - 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. - raw_content (bytes): - The raw content of the document. This field is only - permitted for EXTRACTIVE_QA and FAQ knowledge types. - 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_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 (Sequence[google.cloud.dialogflow_v2beta1.types.Document.MetadataEntry]): - 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. - """ - class KnowledgeType(proto.Enum): - r"""The knowledge type of document content.""" - KNOWLEDGE_TYPE_UNSPECIFIED = 0 - FAQ = 1 - EXTRACTIVE_QA = 2 - ARTICLE_SUGGESTION = 3 - SMART_REPLY = 4 - - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - mime_type = proto.Field( - proto.STRING, - number=3, - ) - knowledge_types = proto.RepeatedField( - proto.ENUM, - number=4, - enum=KnowledgeType, - ) - content_uri = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - content = proto.Field( - proto.STRING, - number=6, - oneof='source', - ) - raw_content = proto.Field( - proto.BYTES, - number=9, - oneof='source', - ) - enable_auto_reload = proto.Field( - proto.BOOL, - number=11, - ) - latest_reload_status = proto.Field( - proto.MESSAGE, - number=12, - message=ReloadStatus, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - - -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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - Attributes: - documents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - document = proto.Field( - proto.MESSAGE, - number=2, - message='Document', - ) - import_gcs_custom_metadata = proto.Field( - proto.BOOL, - number=3, - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - 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:////*.``. - 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 = proto.Field( - proto.STRING, - number=1, - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=gcs.GcsSources, - ) - document_template = proto.Field( - proto.MESSAGE, - number=3, - message='ImportDocumentTemplate', - ) - import_gcs_custom_metadata = proto.Field( - proto.BOOL, - number=4, - ) - - -class ImportDocumentTemplate(proto.Message): - r"""The template used for importing documents. - Attributes: - mime_type (str): - Required. The MIME type of the document. - knowledge_types (Sequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): - Required. The knowledge type of document - content. - metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - knowledge_types = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Document.KnowledgeType', - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - Attributes: - warnings (Sequence[google.rpc.status_pb2.Status]): - Includes details about skipped documents or - any other warnings. - """ - - warnings = 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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Document', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class KnowledgeOperationMetadata(proto.Message): - r"""Metadata in google::longrunning::Operation for Knowledge - operations. - - Attributes: - state (google.cloud.dialogflow_v2beta1.types.KnowledgeOperationMetadata.State): - Required. Output only. The current state of - this operation. - """ - class State(proto.Enum): - r"""States of the operation.""" - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - DONE = 3 - - state = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - - -class ReloadDocumentRequest(proto.Message): - r"""Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - - 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. - 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 = proto.Field( - proto.STRING, - number=1, - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message=gcs.GcsSource, - ) - import_gcs_custom_metadata = proto.Field( - proto.BOOL, - number=4, - ) - - -__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 ff36c8fdd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py +++ /dev/null @@ -1,586 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - '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 (Sequence[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.""" - 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). - """ - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Entity, - ) - enable_fuzzy_extraction = proto.Field( - proto.BOOL, - number=7, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.MESSAGE, - number=2, - message='EntityType', - ) - language_code = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='EntityType', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_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 = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - 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://". - entity_type_batch_inline (google.cloud.dialogflow_v2beta1.types.EntityTypeBatch): - The collection of entity types 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type_batch_uri = proto.Field( - proto.STRING, - number=2, - oneof='entity_type_batch', - ) - entity_type_batch_inline = proto.Field( - proto.MESSAGE, - number=3, - oneof='entity_type_batch', - message='EntityTypeBatch', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class BatchUpdateEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - Attributes: - entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): - The collection of updated or created entity - types. - """ - - entity_types = 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 (Sequence[str]): - Required. The names entity types to delete. All names must - point to the same agent as ``parent``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entity_type_names = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - entity_values = proto.RepeatedField( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class EntityTypeBatch(proto.Message): - r"""This message is a wrapper around a collection of entity - types. - - Attributes: - entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): - A collection of entity types. - """ - - entity_types = 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 2142e07f6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py +++ /dev/null @@ -1,459 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - """ - STATE_UNSPECIFIED = 0 - STOPPED = 1 - LOADING = 2 - RUNNING = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - agent_version = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - text_to_speech_settings = proto.Field( - proto.MESSAGE, - number=7, - message='TextToSpeechSettings', - ) - fulfillment = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_fulfillment.Fulfillment, - ) - - -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 (Sequence[google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): - Optional. Configuration of how speech should - be synthesized, mapping from language - (https://cloud.google.com/dialogflow/docs/reference/language) - to SynthesizeSpeechConfig. - """ - - enable_text_to_speech = proto.Field( - proto.BOOL, - number=1, - ) - output_audio_encoding = proto.Field( - proto.ENUM, - number=2, - enum=audio_config.OutputAudioEncoding, - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=3, - ) - synthesize_speech_configs = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=audio_config.SynthesizeSpeechConfig, - ) - - -class ListEnvironmentsRequest(proto.Message): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - Attributes: - environments (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. - - Attributes: - name (str): - Required. The name of the environment. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. - - Attributes: - parent (str): - Required. The agent to create an environment for. Supported - formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - environment (google.cloud.dialogflow_v2beta1.types.Environment): - Required. The environment to create. - environment_id (str): - Required. The unique id of the new - environment. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - environment_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. - - Attributes: - environment (google.cloud.dialogflow_v2beta1.types.Environment): - Required. The environment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - allow_load_to_draft_and_discard_changes (bool): - Optional. This field is used to prevent accidental overwrite - of the draft environment, which is an operation that cannot - be undone. To confirm that the caller desires this - overwrite, this field must be explicitly set to true when - updating the draft environment (environment ID = ``-``). - """ - - environment = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_load_to_draft_and_discard_changes = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. - - Attributes: - name (str): - Required. The name of the environment to delete. / Format: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEnvironmentHistoryRequest(proto.Message): - r"""The request message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - - Attributes: - parent (str): - Required. The name of the environment to retrieve history - for. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - page_size (int): - Optional. The maximum number of items to - return in a single page. By default 100 and at - most 1000. - page_token (str): - Optional. The next_page_token value returned from a previous - list request. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class EnvironmentHistory(proto.Message): - r"""The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - - Attributes: - parent (str): - Output only. The name of the environment this history is - for. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - entries (Sequence[google.cloud.dialogflow_v2beta1.types.EnvironmentHistory.Entry]): - Output only. The list of agent environments. There will be a - maximum number of items returned based on the page_size - field in the request. - next_page_token (str): - Output only. Token to retrieve the next page - of results, or empty if there are no more - results in the list. - """ - - class Entry(proto.Message): - r"""Represents an environment history entry. - Attributes: - agent_version (str): - The agent version loaded into this - environment history entry. - description (str): - The developer-provided description for this - environment history entry. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of this environment history - entry. - """ - - agent_version = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - @property - def raw_page(self): - return self - - parent = proto.Field( - proto.STRING, - number=1, - ) - entries = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Entry, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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 2f44f0d8d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py +++ /dev/null @@ -1,62 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'GcsSources', - 'GcsSource', - }, -) - - -class GcsSources(proto.Message): - r"""Google Cloud Storage locations for the inputs. - Attributes: - uris (Sequence[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 = 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 = 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 0473ecffe..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py +++ /dev/null @@ -1,69 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - participant = proto.Field( - proto.STRING, - number=3, - ) - suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_participant.SuggestionResult, - ) - - -__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 69452e9d1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py +++ /dev/null @@ -1,2124 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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. - """ - 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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Parameter]): - Optional. The collection of parameters - associated with the intent. - messages (Sequence[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 (Sequence[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 (Sequence[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.""" - 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 (Sequence[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.""" - 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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - alias = proto.Field( - proto.STRING, - number=3, - ) - user_defined = proto.Field( - proto.BOOL, - number=4, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum='Intent.TrainingPhrase.Type', - ) - parts = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Intent.TrainingPhrase.Part', - ) - times_added_count = proto.Field( - proto.INT32, - number=4, - ) - - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - value = proto.Field( - proto.STRING, - number=3, - ) - default_value = proto.Field( - proto.STRING, - number=4, - ) - entity_type_display_name = proto.Field( - proto.STRING, - number=5, - ) - mandatory = proto.Field( - proto.BOOL, - number=6, - ) - prompts = proto.RepeatedField( - proto.STRING, - number=7, - ) - is_list = proto.Field( - proto.BOOL, - number=8, - ) - - class Message(proto.Message): - r"""Corresponds to the ``Response`` field in the Dialogflow console. - Attributes: - text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): - Returns a text response. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Displays an image. - quick_replies (google.cloud.dialogflow_v2beta1.types.Intent.Message.QuickReplies): - Displays quick replies. - card (google.cloud.dialogflow_v2beta1.types.Intent.Message.Card): - Displays a card. - payload (google.protobuf.struct_pb2.Struct): - A custom platform-specific response. - simple_responses (google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponses): - Returns a voice or text-only response for - Actions on Google. - basic_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard): - Displays a basic card for Actions on Google. - suggestions (google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestions): - Displays suggestion chips for Actions on - Google. - link_out_suggestion (google.cloud.dialogflow_v2beta1.types.Intent.Message.LinkOutSuggestion): - Displays a link out suggestion chip for - Actions on Google. - list_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect): - Displays a list card for Actions on Google. - carousel_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect): - Displays a carousel card for Actions on - Google. - telephony_play_audio (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyPlayAudio): - Plays audio from a file in Telephony Gateway. - telephony_synthesize_speech (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonySynthesizeSpeech): - Synthesizes speech in Telephony Gateway. - telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyTransferCall): - Transfers the call in Telephony Gateway. - 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. - rbm_standalone_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard): - Standalone Rich Business Messaging (RBM) rich - card response. - rbm_carousel_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard): - Rich Business Messaging (RBM) carousel rich - card response. - browse_carousel_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard): - Browse carousel card for Actions on Google. - table_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCard): - Table card for Actions on Google. - media_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent): - The media content card for Actions on Google. - 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. - """ - 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 (Sequence[str]): - Optional. The collection of the agent's - responses. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class Image(proto.Message): - r"""The image response message. - Attributes: - image_uri (str): - Optional. The public URI to an image file. - 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 = proto.Field( - proto.STRING, - number=1, - ) - accessibility_text = proto.Field( - proto.STRING, - number=2, - ) - - class QuickReplies(proto.Message): - r"""The quick replies response message. - Attributes: - title (str): - Optional. The title of the collection of - quick replies. - quick_replies (Sequence[str]): - Optional. The collection of quick replies. - """ - - title = proto.Field( - proto.STRING, - number=1, - ) - quick_replies = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Card(proto.Message): - r"""The card response message. - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - image_uri (str): - Optional. The public URI to an image file for - the card. - buttons (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - postback = proto.Field( - proto.STRING, - number=2, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - image_uri = proto.Field( - proto.STRING, - number=3, - ) - buttons = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.Card.Button', - ) - - class SimpleResponse(proto.Message): - r"""The simple response message containing speech or text. - Attributes: - text_to_speech (str): - One of text_to_speech or ssml must be provided. The plain - 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 = proto.Field( - proto.STRING, - number=1, - ) - ssml = proto.Field( - proto.STRING, - number=2, - ) - display_text = proto.Field( - proto.STRING, - number=3, - ) - - class SimpleResponses(proto.Message): - r"""The collection of simple response candidates. This message in - ``QueryResult.fulfillment_messages`` and - ``WebhookResponse.fulfillment_messages`` should contain only one - ``SimpleResponse``. - - Attributes: - simple_responses (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponse]): - Required. The list of simple responses. - """ - - simple_responses = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - open_uri_action = proto.Field( - proto.MESSAGE, - number=2, - message='Intent.Message.BasicCard.Button.OpenUriAction', - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - formatted_text = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - buttons = 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 = proto.Field( - proto.STRING, - number=1, - ) - - class Suggestions(proto.Message): - r"""The collection of suggestions. - Attributes: - suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): - Required. The list of suggested replies. - """ - - suggestions = 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 = proto.Field( - proto.STRING, - number=1, - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - - class ListSelect(proto.Message): - r"""The card for presenting a list of options to select from. - Attributes: - title (str): - Optional. The overall title of the list. - items (Sequence[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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - items = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.ListSelect.Item', - ) - subtitle = proto.Field( - proto.STRING, - number=3, - ) - - class CarouselSelect(proto.Message): - r"""The card for presenting a carousel of options to select from. - Attributes: - items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): - Required. Carousel items. - """ - - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - items = 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 (Sequence[str]): - Optional. A list of synonyms that can also be - used to trigger this item in dialog. - """ - - key = proto.Field( - proto.STRING, - number=1, - ) - synonyms = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class TelephonyPlayAudio(proto.Message): - r"""Plays audio from a file in Telephony Gateway. - Attributes: - audio_uri (str): - Required. URI to a Google Cloud Storage object containing - 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 = 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. - - Attributes: - text (str): - The raw text to be synthesized. - ssml (str): - The SSML to be synthesized. For more information, see - `SSML `__. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - ssml = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - - class TelephonyTransferCall(proto.Message): - r"""Transfers the call in Telephony Gateway. - Attributes: - phone_number (str): - Required. The phone number to transfer the call to in `E.164 - format `__. - - We currently only allow transferring to US numbers - (+1xxxyyyzzzz). - """ - - phone_number = proto.Field( - proto.STRING, - number=1, - ) - - class RbmText(proto.Message): - r"""Rich Business Messaging (RBM) text response with suggestions. - Attributes: - text (str): - Required. Text sent and displayed to the - user. - rbm_suggestion (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): - Optional. One or more suggestions to show to - the user. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - rbm_suggestion = 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 (Sequence[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.""" - CARD_WIDTH_UNSPECIFIED = 0 - SMALL = 1 - MEDIUM = 2 - - card_width = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.RbmCarouselCard.CardWidth', - ) - card_contents = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.RbmCardContent', - ) - - 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.""" - CARD_ORIENTATION_UNSPECIFIED = 0 - HORIZONTAL = 1 - VERTICAL = 2 - - class ThumbnailImageAlignment(proto.Enum): - r"""Thumbnail preview alignment for standalone cards with - horizontal layout. - """ - THUMBNAIL_IMAGE_ALIGNMENT_UNSPECIFIED = 0 - LEFT = 1 - RIGHT = 2 - - card_orientation = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.RbmStandaloneCard.CardOrientation', - ) - thumbnail_image_alignment = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment', - ) - card_content = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.RbmCardContent', - ) - - class RbmCardContent(proto.Message): - r"""Rich Business Messaging (RBM) Card content - Attributes: - title (str): - Optional. Title of the card (at most 200 - 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 (Sequence[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""" - HEIGHT_UNSPECIFIED = 0 - SHORT = 1 - MEDIUM = 2 - TALL = 3 - - file_uri = proto.Field( - proto.STRING, - number=1, - ) - thumbnail_uri = proto.Field( - proto.STRING, - number=2, - ) - height = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.RbmCardContent.RbmMedia.Height', - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - media = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.RbmCardContent.RbmMedia', - ) - suggestions = 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). - - Attributes: - reply (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedReply): - Predefined replies for user to select instead - of typing - action (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction): - Predefined client side actions that user can - choose - """ - - reply = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion', - message='Intent.Message.RbmSuggestedReply', - ) - action = 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 = proto.Field( - proto.STRING, - number=1, - ) - postback_data = proto.Field( - proto.STRING, - number=2, - ) - - class RbmSuggestedAction(proto.Message): - r"""Rich Business Messaging (RBM) suggested client-side action - that the user can choose from the card. - - 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 - open_url (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri): - Suggested client side action: Open a URI on - device - share_location (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation): - Suggested client side action: Share user - location - """ - - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - - class RbmSuggestedActionShareLocation(proto.Message): - r"""Opens the device's location chooser so the user can pick a - location to send back to the agent. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - postback_data = proto.Field( - proto.STRING, - number=2, - ) - dial = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial', - ) - open_url = proto.Field( - proto.MESSAGE, - number=4, - oneof='action', - message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri', - ) - share_location = proto.Field( - proto.MESSAGE, - number=5, - 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaObject]): - Required. List of media objects. - """ - class ResponseMediaType(proto.Enum): - r"""Format of response media type.""" - RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 - AUDIO = 1 - - class ResponseMediaObject(proto.Message): - r"""Response media object for media content card. - 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. - icon (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. Icon to display above media - content. - content_url (str): - Required. Url where the media is stored. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - large_image = proto.Field( - proto.MESSAGE, - number=3, - oneof='image', - message='Intent.Message.Image', - ) - icon = proto.Field( - proto.MESSAGE, - number=4, - oneof='image', - message='Intent.Message.Image', - ) - content_url = proto.Field( - proto.STRING, - number=5, - ) - - media_type = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.MediaContent.ResponseMediaType', - ) - media_objects = 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 (Sequence[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. - """ - 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.""" - URL_TYPE_HINT_UNSPECIFIED = 0 - AMP_ACTION = 1 - AMP_CONTENT = 2 - - url = proto.Field( - proto.STRING, - number=1, - ) - url_type_hint = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', - ) - - open_uri_action = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - image = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - footer = proto.Field( - proto.STRING, - number=5, - ) - - items = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', - ) - image_display_options = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties]): - Optional. Display properties for the columns - in this table. - rows (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardRow]): - Optional. Rows in this table of data. - buttons (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): - Optional. List of buttons for the card. - """ - - title = proto.Field( - proto.STRING, - number=1, - ) - subtitle = proto.Field( - proto.STRING, - number=2, - ) - image = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.Image', - ) - column_properties = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.ColumnProperties', - ) - rows = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.TableCardRow', - ) - buttons = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Intent.Message.BasicCard.Button', - ) - - 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.""" - HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 - LEADING = 1 - CENTER = 2 - TRAILING = 3 - - header = proto.Field( - proto.STRING, - number=1, - ) - horizontal_alignment = 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 (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.TableCardCell', - ) - divider_after = 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 = proto.Field( - proto.STRING, - number=1, - ) - - text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='Intent.Message.Text', - ) - image = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Intent.Message.Image', - ) - quick_replies = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message='Intent.Message.QuickReplies', - ) - card = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message='Intent.Message.Card', - ) - payload = proto.Field( - proto.MESSAGE, - number=5, - oneof='message', - message=struct_pb2.Struct, - ) - simple_responses = proto.Field( - proto.MESSAGE, - number=7, - oneof='message', - message='Intent.Message.SimpleResponses', - ) - basic_card = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message='Intent.Message.BasicCard', - ) - suggestions = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message='Intent.Message.Suggestions', - ) - link_out_suggestion = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message='Intent.Message.LinkOutSuggestion', - ) - list_select = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message='Intent.Message.ListSelect', - ) - carousel_select = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message='Intent.Message.CarouselSelect', - ) - telephony_play_audio = proto.Field( - proto.MESSAGE, - number=13, - oneof='message', - message='Intent.Message.TelephonyPlayAudio', - ) - telephony_synthesize_speech = proto.Field( - proto.MESSAGE, - number=14, - oneof='message', - message='Intent.Message.TelephonySynthesizeSpeech', - ) - telephony_transfer_call = proto.Field( - proto.MESSAGE, - number=15, - oneof='message', - message='Intent.Message.TelephonyTransferCall', - ) - rbm_text = proto.Field( - proto.MESSAGE, - number=18, - oneof='message', - message='Intent.Message.RbmText', - ) - rbm_standalone_rich_card = proto.Field( - proto.MESSAGE, - number=19, - oneof='message', - message='Intent.Message.RbmStandaloneCard', - ) - rbm_carousel_rich_card = proto.Field( - proto.MESSAGE, - number=20, - oneof='message', - message='Intent.Message.RbmCarouselCard', - ) - browse_carousel_card = proto.Field( - proto.MESSAGE, - number=22, - oneof='message', - message='Intent.Message.BrowseCarouselCard', - ) - table_card = proto.Field( - proto.MESSAGE, - number=23, - oneof='message', - message='Intent.Message.TableCard', - ) - media_content = proto.Field( - proto.MESSAGE, - number=24, - oneof='message', - message='Intent.Message.MediaContent', - ) - platform = proto.Field( - proto.ENUM, - number=6, - enum='Intent.Message.Platform', - ) - - class FollowupIntentInfo(proto.Message): - r"""Represents a single followup intent in the chain. - Attributes: - followup_intent_name (str): - The unique identifier of the followup intent. Format: - ``projects//agent/intents/``. - parent_followup_intent_name (str): - The unique identifier of the followup intent's parent. - Format: ``projects//agent/intents/``. - """ - - followup_intent_name = proto.Field( - proto.STRING, - number=1, - ) - parent_followup_intent_name = proto.Field( - proto.STRING, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - webhook_state = proto.Field( - proto.ENUM, - number=6, - enum=WebhookState, - ) - priority = proto.Field( - proto.INT32, - number=3, - ) - is_fallback = proto.Field( - proto.BOOL, - number=4, - ) - ml_enabled = proto.Field( - proto.BOOL, - number=5, - ) - ml_disabled = proto.Field( - proto.BOOL, - number=19, - ) - live_agent_handoff = proto.Field( - proto.BOOL, - number=20, - ) - end_interaction = proto.Field( - proto.BOOL, - number=21, - ) - input_context_names = proto.RepeatedField( - proto.STRING, - number=7, - ) - events = proto.RepeatedField( - proto.STRING, - number=8, - ) - training_phrases = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=TrainingPhrase, - ) - action = proto.Field( - proto.STRING, - number=10, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=context.Context, - ) - reset_contexts = proto.Field( - proto.BOOL, - number=12, - ) - parameters = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Parameter, - ) - messages = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=Message, - ) - default_response_platforms = proto.RepeatedField( - proto.ENUM, - number=15, - enum=Message.Platform, - ) - root_followup_intent_name = proto.Field( - proto.STRING, - number=16, - ) - parent_followup_intent_name = proto.Field( - proto.STRING, - number=17, - ) - followup_intent_info = 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``. - 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - Attributes: - intents (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = 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 = proto.Field( - proto.STRING, - number=1, - ) - intent = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - intent_view = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - intent_view = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateIntentsRequest(proto.Message): - r"""The request message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - - 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://". - intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): - The collection of intents 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. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - intent_batch_uri = proto.Field( - proto.STRING, - number=2, - oneof='intent_batch', - ) - intent_batch_inline = proto.Field( - proto.MESSAGE, - number=3, - oneof='intent_batch', - message='IntentBatch', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - intent_view = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): - The collection of updated or created intents. - """ - - intents = 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): - Required. The collection of intents to delete. Only intent - ``name`` must be filled in. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - intents = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent', - ) - - -class IntentBatch(proto.Message): - r"""This message is a wrapper around a collection of intents. - Attributes: - intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): - A collection of intents. - """ - - intents = 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 dca009b2d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py +++ /dev/null @@ -1,257 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - '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 = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesRequest(proto.Message): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesResponse(proto.Message): - r"""Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - knowledge_bases (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - knowledge_base = 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 = proto.Field( - proto.STRING, - number=1, - ) - force = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - update_mask = 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 90b5a7b46..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py +++ /dev/null @@ -1,1473 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import 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', - 'OutputAudio', - 'AutomatedAgentReply', - 'SuggestionFeature', - 'AnalyzeContentRequest', - 'DtmfParameters', - 'AnalyzeContentResponse', - '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. - """ - class Role(proto.Enum): - r"""Enumeration of the roles a participant can play in a - conversation. - """ - ROLE_UNSPECIFIED = 0 - HUMAN_AGENT = 1 - AUTOMATED_AGENT = 2 - END_USER = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - role = proto.Field( - proto.ENUM, - number=2, - enum=Role, - ) - obfuscated_external_user_id = proto.Field( - proto.STRING, - number=7, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - content = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - participant = proto.Field( - proto.STRING, - number=4, - ) - participant_role = proto.Field( - proto.ENUM, - number=5, - enum='Participant.Role', - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - send_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - message_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='MessageAnnotation', - ) - sentiment_analysis = proto.Field( - proto.MESSAGE, - number=8, - message=session.SentimentAnalysisResult, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListParticipantsResponse(proto.Message): - r"""The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - Attributes: - participants (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Participant', - ) - next_page_token = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Participant', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -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 = proto.Field( - proto.MESSAGE, - number=1, - message=audio_config.OutputAudioConfig, - ) - audio = proto.Field( - proto.BYTES, - number=2, - ) - - -class AutomatedAgentReply(proto.Message): - r"""Represents a response from an automated agent. - Attributes: - detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): - Response of the Dialogflow - [Sessions.DetectIntent][google.cloud.dialogflow.v2beta1.Sessions.DetectIntent] - call. - response_messages (Sequence[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/``. - event (str): - Event name if an event is triggered for the - query. - cx_session_parameters (google.protobuf.struct_pb2.Struct): - The collection of current Dialogflow CX agent - session parameters at the time of this response. - """ - - detect_intent_response = proto.Field( - proto.MESSAGE, - number=1, - oneof='response', - message=session.DetectIntentResponse, - ) - response_messages = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ResponseMessage', - ) - intent = proto.Field( - proto.STRING, - number=4, - oneof='match', - ) - event = proto.Field( - proto.STRING, - number=5, - oneof='match', - ) - cx_session_parameters = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -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.""" - TYPE_UNSPECIFIED = 0 - ARTICLE_SUGGESTION = 1 - FAQ = 2 - SMART_REPLY = 3 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - - -class AnalyzeContentRequest(proto.Message): - r"""The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - 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. - event_input (google.cloud.dialogflow_v2beta1.types.EventInput): - An input event to send to Dialogflow. - 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. - 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 = proto.Field( - proto.STRING, - number=1, - ) - text_input = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message=session.TextInput, - ) - event_input = proto.Field( - proto.MESSAGE, - number=8, - oneof='input', - message=session.EventInput, - ) - reply_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=audio_config.OutputAudioConfig, - ) - query_params = proto.Field( - proto.MESSAGE, - number=9, - message=session.QueryParameters, - ) - message_send_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - request_id = 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 = 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 (Sequence[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 (Sequence[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. - """ - - reply_text = proto.Field( - proto.STRING, - number=1, - ) - reply_audio = proto.Field( - proto.MESSAGE, - number=2, - message='OutputAudio', - ) - automated_agent_reply = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentReply', - ) - message = proto.Field( - proto.MESSAGE, - number=5, - message='Message', - ) - human_agent_suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='SuggestionResult', - ) - end_user_suggestion_results = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - dtmf_parameters = proto.Field( - proto.MESSAGE, - number=9, - message='DtmfParameters', - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - formatted_value = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - - -class MessageAnnotation(proto.Message): - r"""Represents the result of annotation for the message. - Attributes: - parts (Sequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): - Optional. The collection of annotated message parts ordered - 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnnotatedMessagePart', - ) - contain_entities = 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 (Sequence[str]): - Output only. Article snippets. - metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ArticleAnswer.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - snippets = proto.RepeatedField( - proto.STRING, - number=3, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - -class FaqAnswer(proto.Message): - r"""Represents answer from "frequently asked questions". - Attributes: - answer (str): - The piece of text from the ``source`` knowledge base - 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 (Sequence[google.cloud.dialogflow_v2beta1.types.FaqAnswer.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - question = proto.Field( - proto.STRING, - number=3, - ) - source = proto.Field( - proto.STRING, - number=4, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - -class SmartReplyAnswer(proto.Message): - r"""Represents a smart reply answer. - Attributes: - reply (str): - The content of the reply. - 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 = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - answer_record = proto.Field( - proto.STRING, - number=3, - ) - - -class SuggestionResult(proto.Message): - 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]. - - Attributes: - error (google.rpc.status_pb2.Status): - Error status if the request failed. - suggest_articles_response (google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse): - SuggestArticlesResponse if request is for - ARTICLE_SUGGESTION. - suggest_faq_answers_response (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse): - SuggestFaqAnswersResponse if request is for FAQ_ANSWER. - suggest_smart_replies_response (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse): - SuggestSmartRepliesResponse if request is for SMART_REPLY. - """ - - error = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion_response', - message=status_pb2.Status, - ) - suggest_articles_response = proto.Field( - proto.MESSAGE, - number=2, - oneof='suggestion_response', - message='SuggestArticlesResponse', - ) - suggest_faq_answers_response = proto.Field( - proto.MESSAGE, - number=3, - oneof='suggestion_response', - message='SuggestFaqAnswersResponse', - ) - suggest_smart_replies_response = proto.Field( - proto.MESSAGE, - number=4, - 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestArticlesResponse(proto.Message): - r"""The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - Attributes: - article_answers (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ArticleAnswer', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = 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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestFaqAnswersResponse(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - Attributes: - faq_answers (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FaqAnswer', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = 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 = proto.Field( - proto.STRING, - number=1, - ) - current_text_input = proto.Field( - proto.MESSAGE, - number=4, - message=session.TextInput, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestSmartRepliesResponse(proto.Message): - r"""The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - Attributes: - smart_reply_answers (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SmartReplyAnswer', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class Suggestion(proto.Message): - r"""Represents a suggestion for a human agent. - Attributes: - name (str): - Output only. The name of this suggestion. Format: - ``projects//locations//conversations//participants/*/suggestions/``. - articles (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article]): - Output only. Articles ordered by score in - descending order. - faq_answers (Sequence[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 (Sequence[str]): - Output only. Article snippets. - metadata (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - snippets = proto.RepeatedField( - proto.STRING, - number=3, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - class FaqAnswer(proto.Message): - r"""Represents suggested answer from "frequently asked - 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 (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.FaqAnswer.MetadataEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - question = proto.Field( - proto.STRING, - number=3, - ) - source = proto.Field( - proto.STRING, - number=4, - ) - metadata = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record = proto.Field( - proto.STRING, - number=6, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - articles = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Article, - ) - faq_answers = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=FaqAnswer, - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - latest_message = 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListSuggestionsResponse(proto.Message): - r"""The response message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - Attributes: - suggestions (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Suggestion', - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class CompileSuggestionResponse(proto.Message): - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Suggestion', - ) - latest_message = proto.Field( - proto.STRING, - number=2, - ) - context_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ResponseMessage(proto.Message): - r"""Response messages from an automated agent. - Attributes: - text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): - Returns a text response. - payload (google.protobuf.struct_pb2.Struct): - Returns a response containing a custom, - platform-specific payload. - live_agent_handoff (google.cloud.dialogflow_v2beta1.types.ResponseMessage.LiveAgentHandoff): - Hands off conversation to a live agent. - end_interaction (google.cloud.dialogflow_v2beta1.types.ResponseMessage.EndInteraction): - A signal that indicates the interaction with - the Dialogflow agent has ended. - """ - - class Text(proto.Message): - r"""The text response message. - Attributes: - text (Sequence[str]): - A collection of text responses. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=struct_pb2.Struct, - ) - - class EndInteraction(proto.Message): - r"""Indicates that interaction with the Dialogflow agent has - ended. - """ - - text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message=Text, - ) - payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message=struct_pb2.Struct, - ) - live_agent_handoff = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message=LiveAgentHandoff, - ) - end_interaction = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message=EndInteraction, - ) - - -__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 f63b3eb9c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py +++ /dev/null @@ -1,1151 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio = proto.Field( - proto.BYTES, - number=5, - ) - - -class DetectIntentResponse(proto.Message): - r"""The message returned from the DetectIntent method. - Attributes: - response_id (str): - The unique identifier of the response. It can - 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - query_result = proto.Field( - proto.MESSAGE, - number=2, - message='QueryResult', - ) - alternative_query_results = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='QueryResult', - ) - webhook_status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - output_audio = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config = 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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.dialogflow_v2beta1.types.QueryParameters.WebhookHeadersEntry]): - 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 = proto.Field( - proto.STRING, - number=1, - ) - geo_location = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - contexts = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=context.Context, - ) - reset_contexts = proto.Field( - proto.BOOL, - number=4, - ) - session_entity_types = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) - payload = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - knowledge_base_names = proto.RepeatedField( - proto.STRING, - number=12, - ) - sentiment_analysis_request_config = proto.Field( - proto.MESSAGE, - number=10, - message='SentimentAnalysisRequestConfig', - ) - sub_agents = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=agent.SubAgent, - ) - webhook_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - - -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. - - Attributes: - audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - text (google.cloud.dialogflow_v2beta1.types.TextInput): - The natural language text to be processed. - event (google.cloud.dialogflow_v2beta1.types.EventInput): - The event to be processed. - dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - """ - - audio_config = proto.Field( - proto.MESSAGE, - number=1, - oneof='input', - message=gcd_audio_config.InputAudioConfig, - ) - text = proto.Field( - proto.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - event = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='EventInput', - ) - dtmf = proto.Field( - proto.MESSAGE, - number=4, - 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. - 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 (Sequence[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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=15, - ) - speech_recognition_confidence = proto.Field( - proto.FLOAT, - number=2, - ) - action = proto.Field( - proto.STRING, - number=3, - ) - parameters = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - all_required_params_present = proto.Field( - proto.BOOL, - number=5, - ) - fulfillment_text = proto.Field( - proto.STRING, - number=6, - ) - fulfillment_messages = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) - webhook_source = proto.Field( - proto.STRING, - number=8, - ) - webhook_payload = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=context.Context, - ) - intent = proto.Field( - proto.MESSAGE, - number=11, - message=gcd_intent.Intent, - ) - intent_detection_confidence = proto.Field( - proto.FLOAT, - number=12, - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=14, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = proto.Field( - proto.MESSAGE, - number=17, - message='SentimentAnalysisResult', - ) - knowledge_answers = proto.Field( - proto.MESSAGE, - number=18, - message='KnowledgeAnswers', - ) - - -class KnowledgeAnswers(proto.Message): - r"""Represents the result of querying a Knowledge base. - Attributes: - answers (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): - A list of answers from Knowledge Connector. - """ - - 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. - """ - MATCH_CONFIDENCE_LEVEL_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - - source = proto.Field( - proto.STRING, - number=1, - ) - faq_question = proto.Field( - proto.STRING, - number=2, - ) - answer = proto.Field( - proto.STRING, - number=3, - ) - match_confidence_level = proto.Field( - proto.ENUM, - number=4, - enum='KnowledgeAnswers.Answer.MatchConfidenceLevel', - ) - match_confidence = proto.Field( - proto.FLOAT, - number=5, - ) - - answers = 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 = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - single_utterance = proto.Field( - proto.BOOL, - number=4, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio = 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 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. 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - recognition_result = proto.Field( - proto.MESSAGE, - number=2, - message='StreamingRecognitionResult', - ) - query_result = proto.Field( - proto.MESSAGE, - number=3, - message='QueryResult', - ) - alternative_query_results = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='QueryResult', - ) - webhook_status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - output_audio = proto.Field( - proto.BYTES, - number=5, - ) - output_audio_config = 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. - - Example: - - 1. transcript: "tube" - - 2. transcript: "to be a" - - 3. transcript: "to be" - - 4. transcript: "to be or not to be" is_final: true - - 5. transcript: " that's" - - 6. transcript: " that is" - - 7. message_type: ``END_OF_SINGLE_UTTERANCE`` - - 8. transcript: " that is the question" is_final: true - - Only two of the responses contain final results (#4 and #8 indicated - by ``is_final: true``). Concatenating these generates the full - transcript: "to be or not to be that is the question". - - In each response we populate: - - - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. - - - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. - - 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 (Sequence[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``. - 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.""" - MESSAGE_TYPE_UNSPECIFIED = 0 - TRANSCRIPT = 1 - END_OF_SINGLE_UTTERANCE = 2 - - message_type = proto.Field( - proto.ENUM, - number=1, - enum=MessageType, - ) - transcript = proto.Field( - proto.STRING, - number=2, - ) - is_final = proto.Field( - proto.BOOL, - number=3, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - stability = proto.Field( - proto.FLOAT, - number=6, - ) - speech_word_info = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) - speech_end_offset = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - dtmf_digits = 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. - 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 = proto.Field( - proto.STRING, - number=1, - ) - language_code = 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class SentimentAnalysisRequestConfig(proto.Message): - r"""Configures the types of sentiment analysis to perform. - Attributes: - analyze_query_text_sentiment (bool): - Instructs the service to perform sentiment analysis on - ``query_text``. If not provided, sentiment analysis is not - performed on ``query_text``. - """ - - analyze_query_text_sentiment = 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 = 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. - - 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 = proto.Field( - proto.FLOAT, - number=1, - ) - magnitude = 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 4442b9004..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py +++ /dev/null @@ -1,274 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 (Sequence[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.""" - ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 - ENTITY_OVERRIDE_MODE_OVERRIDE = 1 - ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - entity_override_mode = proto.Field( - proto.ENUM, - number=2, - enum=EntityOverrideMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=entity_type.EntityType.Entity, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - session_entity_type = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - update_mask = 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 = 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 9e80a2e22..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py +++ /dev/null @@ -1,93 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__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 (Sequence[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 messsage. - """ - class Severity(proto.Enum): - r"""Represents a level of severity.""" - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - CRITICAL = 4 - - severity = proto.Field( - proto.ENUM, - number=1, - enum=Severity, - ) - entries = proto.RepeatedField( - proto.STRING, - number=3, - ) - error_message = proto.Field( - proto.STRING, - number=4, - ) - - -class ValidationResult(proto.Message): - r"""Represents the output of agent validation. - Attributes: - validation_errors (Sequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): - Contains all validation errors. - """ - - validation_errors = 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/webhook.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py deleted file mode 100644 index 2d91bd504..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py +++ /dev/null @@ -1,260 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.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 (Sequence[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 = proto.Field( - proto.STRING, - number=4, - ) - response_id = proto.Field( - proto.STRING, - number=1, - ) - query_result = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_session.QueryResult, - ) - alternative_query_results = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_session.QueryResult, - ) - original_detect_intent_request = proto.Field( - proto.MESSAGE, - number=3, - message='OriginalDetectIntentRequest', - ) - - -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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - fulfillment_messages = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=intent.Intent.Message, - ) - source = proto.Field( - proto.STRING, - number=3, - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - output_contexts = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=context.Context, - ) - followup_event_input = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_session.EventInput, - ) - live_agent_handoff = proto.Field( - proto.BOOL, - number=7, - ) - end_interaction = proto.Field( - proto.BOOL, - number=8, - ) - session_entity_types = 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 = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - payload = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/mypy.ini b/owl-bot-staging/v2beta1/mypy.ini deleted file mode 100644 index 4505b4854..000000000 --- a/owl-bot-staging/v2beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2beta1/noxfile.py b/owl-bot-staging/v2beta1/noxfile.py deleted file mode 100644 index 7c973f2b5..000000000 --- a/owl-bot-staging/v2beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/dialogflow_v2beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 0a8e20f0b..000000000 --- a/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py +++ /dev/null @@ -1,263 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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', 'message_send_time', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_create_messages': ('parent', 'requests', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_environment': ('parent', 'environment', 'environment_id', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'create_version': ('parent', 'version', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_environment': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'delete_version': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_answer_record': ('name', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_environment': ('name', ), - 'get_environment_history': ('parent', 'page_size', 'page_token', ), - 'get_fulfillment': ('name', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'get_version': ('name', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), - 'list_answer_records': ('parent', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_versions': ('parent', 'page_size', 'page_token', ), - 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), - 'update_fulfillment': ('fulfillment', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - 'update_version': ('version', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - 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: not a.keyword.value 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 4601e7528..000000000 --- a/owl-bot-staging/v2beta1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-dialogflow', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2beta1/tests/__init__.py b/owl-bot-staging/v2beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc4..000000000 --- a/owl-bot-staging/v2beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc4..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 9f0518ac0..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py +++ /dev/null @@ -1,3145 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.agents import AgentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.agents import AgentsClient -from google.cloud.dialogflow_v2beta1.services.agents import pagers -from google.cloud.dialogflow_v2beta1.services.agents import transports -from google.cloud.dialogflow_v2beta1.services.agents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.agents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import agent -from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent -from google.cloud.dialogflow_v2beta1.types import validation_result -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - AgentsClient, - AgentsAsyncClient, -]) -def test_agents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AgentsClient, - AgentsAsyncClient, -]) -def test_agents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_agents_client_get_transport_class(): - transport = AgentsClient.get_transport_class() - available_transports = [ - transports.AgentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): - 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.2552, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - tier=agent.Agent.Tier.TIER_STANDARD, - ) - response = client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -def test_get_agent_from_dict(): - test_get_agent(request_type=dict) - - -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.2552, - 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.2552, 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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): - 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.2552, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - tier=gcd_agent.Agent.Tier.TIER_STANDARD, - ) - response = client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -def test_set_agent_from_dict(): - test_set_agent(request_type=dict) - - -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.2552, - 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.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -@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 = 'agent.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - call.return_value = gcd_agent.Agent() - client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=agent.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 = 'agent.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) - - # Establish that the underlying gRPC stub method was called. - 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=agent.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] - assert args[0].agent == gcd_agent.Agent(parent='parent_value') - - -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] - assert args[0].agent == gcd_agent.Agent(parent='parent_value') - - -@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'), - ) - - -def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): - 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_from_dict(): - test_delete_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): - 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_from_dict(): - test_search_agents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) - -def test_search_agents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): - 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_from_dict(): - test_train_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): - 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_from_dict(): - test_export_agent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): - 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_from_dict(): - test_import_agent(request_type=dict) - - -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'] - - -def test_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): - 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_from_dict(): - test_restore_agent(request_type=dict) - - -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'] - - -def test_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): - 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_from_dict(): - test_get_validation_result(request_type=dict) - - -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'] - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_agents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_agents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_agents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AgentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AgentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_agents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_agents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_agents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_agents_host_no_port(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_agents_host_with_port(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 e09f748c2..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py +++ /dev/null @@ -1,1814 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.answer_records.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.cloud.dialogflow_v2beta1.types import participant -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - AnswerRecordsClient, - AnswerRecordsAsyncClient, -]) -def test_answer_records_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AnswerRecordsClient, - AnswerRecordsAsyncClient, -]) -def test_answer_records_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_answer_records_client_get_transport_class(): - transport = AnswerRecordsClient.get_transport_class() - available_transports = [ - transports.AnswerRecordsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_get_answer_record(transport: str = 'grpc', request_type=answer_record.GetAnswerRecordRequest): - 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_from_dict(): - test_get_answer_record(request_type=dict) - - -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'] - - -def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): - 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_from_dict(): - test_list_answer_records(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) - -def test_list_answer_records_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_update_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - 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_from_dict(): - test_update_answer_record(request_type=dict) - - -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 = 'answer_record.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=answer_record.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 = 'answer_record.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=answer_record.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] - assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].answer_record == gcd_answer_record.AnswerRecord(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient( - credentials=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']), - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_answer_records_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_answer_records_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AnswerRecordsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_answer_records_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AnswerRecordsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_answer_records_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AnswerRecordsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_answer_records_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_answer_records_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_answer_records_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_answer_records_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_answer_records_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_answer_records_host_no_port(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_answer_records_host_with_port(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 c958070d5..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py +++ /dev/null @@ -1,2595 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.contexts import ContextsAsyncClient -from google.cloud.dialogflow_v2beta1.services.contexts import ContextsClient -from google.cloud.dialogflow_v2beta1.services.contexts import pagers -from google.cloud.dialogflow_v2beta1.services.contexts import transports -from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - ContextsClient, - ContextsAsyncClient, -]) -def test_contexts_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ContextsClient, - ContextsAsyncClient, -]) -def test_contexts_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_contexts_client_get_transport_class(): - transport = ContextsClient.get_transport_class() - available_transports = [ - transports.ContextsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): - 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_from_dict(): - test_list_contexts(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) - -def test_list_contexts_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): - 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_from_dict(): - test_get_context(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): - 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_from_dict(): - test_create_context(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].context == gcd_context.Context(name='name_value') - - -def test_create_context_flattened_error(): - client = ContextsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].context == gcd_context.Context(name='name_value') - - -@pytest.mark.asyncio -async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient( - credentials=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'), - ) - - -def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): - 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_from_dict(): - test_update_context(request_type=dict) - - -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 = 'context.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_context), - '__call__') as call: - call.return_value = gcd_context.Context() - client.update_context(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=context.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 = 'context.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_context), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) - - # Establish that the underlying gRPC stub method was called. - 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=context.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] - assert args[0].context == gcd_context.Context(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].context == gcd_context.Context(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient( - credentials=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']), - ) - - -def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): - 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_from_dict(): - test_delete_context(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): - 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_from_dict(): - test_delete_all_contexts(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_contexts_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_contexts_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_contexts_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ContextsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_contexts_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ContextsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_contexts_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_contexts_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_contexts_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_contexts_host_no_port(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_contexts_host_with_port(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 a2807e988..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py +++ /dev/null @@ -1,2459 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.conversation_profiles.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.cloud.dialogflow_v2beta1.types import participant -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - ConversationProfilesClient, - ConversationProfilesAsyncClient, -]) -def test_conversation_profiles_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ConversationProfilesClient, - ConversationProfilesAsyncClient, -]) -def test_conversation_profiles_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversation_profiles_client_get_transport_class(): - transport = ConversationProfilesClient.get_transport_class() - available_transports = [ - transports.ConversationProfilesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): - 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_from_dict(): - test_list_conversation_profiles(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) - -def test_list_conversation_profiles_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): - 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', - ) - 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' - - -def test_get_conversation_profile_from_dict(): - test_get_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - 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', - ) - 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' - - -def test_create_conversation_profile_from_dict(): - test_create_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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] - assert args[0].parent == 'parent_value' - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - - -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] - assert args[0].parent == 'parent_value' - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - - -@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'), - ) - - -def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - 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', - ) - 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' - - -def test_update_conversation_profile_from_dict(): - test_update_conversation_profile(request_type=dict) - - -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', - )) - 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' - - -@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 = 'conversation_profile.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=conversation_profile.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 = 'conversation_profile.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=conversation_profile.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] - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].conversation_profile == gcd_conversation_profile.ConversationProfile(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - credentials=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']), - ) - - -def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): - 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_from_dict(): - test_delete_conversation_profile(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationProfilesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationProfilesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationProfilesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_conversation_profiles_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversation_profiles_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversation_profiles_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_conversation_profiles_host_no_port(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversation_profiles_host_with_port(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_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 = ConversationProfilesClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "octopus", - "knowledge_base": "oyster", - "document": "nudibranch", - } - 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 = "cuttlefish" - knowledge_base = "mussel" - 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": "winkle", - "knowledge_base": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationProfilesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationProfilesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = ConversationProfilesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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_withDEFAULT_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) 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 dfc4b944b..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py +++ /dev/null @@ -1,2848 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.conversations.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import session -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - ConversationsClient, - ConversationsAsyncClient, -]) -def test_conversations_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ConversationsClient, - ConversationsAsyncClient, -]) -def test_conversations_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversations_client_get_transport_class(): - transport = ConversationsClient.get_transport_class() - available_transports = [ - transports.ConversationsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): - 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_from_dict(): - test_create_conversation(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].conversation == gcd_conversation.Conversation(name='name_value') - - -def test_create_conversation_flattened_error(): - client = ConversationsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].conversation == gcd_conversation.Conversation(name='name_value') - - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - credentials=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'), - ) - - -def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): - 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_from_dict(): - test_list_conversations(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - -def test_list_conversations_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): - 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_from_dict(): - test_get_conversation(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): - 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_from_dict(): - test_complete_conversation(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_batch_create_messages(transport: str = 'grpc', request_type=conversation.BatchCreateMessagesRequest): - 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_from_dict(): - test_batch_create_messages(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): - 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_from_dict(): - test_list_messages(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) - -def test_list_messages_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_conversations_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversations_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_conversations_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_conversations_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ConversationsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_conversations_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_conversations_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_conversations_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversations_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_conversations_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_conversations_host_no_port(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_conversations_host_with_port(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_path(): - project = "squid" - conversation = "clam" - 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": "whelk", - "conversation": "octopus", - } - 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 = "oyster" - conversation_profile = "nudibranch" - 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": "cuttlefish", - "conversation_profile": "mussel", - } - 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 = "winkle" - conversation = "nautilus" - message = "scallop" - 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": "abalone", - "conversation": "squid", - "message": "clam", - } - 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 = "whelk" - 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": "octopus", - } - 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 = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - 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 = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - 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 = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ConversationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - 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 = "scallop" - location = "abalone" - 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": "squid", - "location": "clam", - } - 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_withDEFAULT_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) 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 89df61b8b..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py +++ /dev/null @@ -1,2804 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.documents import DocumentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.documents import DocumentsClient -from google.cloud.dialogflow_v2beta1.services.documents import pagers -from google.cloud.dialogflow_v2beta1.services.documents import transports -from google.cloud.dialogflow_v2beta1.services.documents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.documents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import document -from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.cloud.dialogflow_v2beta1.types import gcs -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - DocumentsClient, - DocumentsAsyncClient, -]) -def test_documents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - DocumentsClient, - DocumentsAsyncClient, -]) -def test_documents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_documents_client_get_transport_class(): - transport = DocumentsClient.get_transport_class() - available_transports = [ - transports.DocumentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): - 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_from_dict(): - test_list_documents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - -def test_list_documents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): - 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, - 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 - - -def test_get_document_from_dict(): - test_get_document(request_type=dict) - - -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, - )) - 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 - - -@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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): - 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_from_dict(): - test_create_document(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].document == gcd_document.Document(name='name_value') - - -def test_create_document_flattened_error(): - client = DocumentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].document == gcd_document.Document(name='name_value') - - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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'), - ) - - -def test_import_documents(transport: str = 'grpc', request_type=document.ImportDocumentsRequest): - 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_from_dict(): - test_import_documents(request_type=dict) - - -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'] - - -def test_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): - 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_from_dict(): - test_delete_document(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): - 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_from_dict(): - test_update_document(request_type=dict) - - -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 = 'document.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=document.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 = 'document.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = 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=document.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] - assert args[0].document == gcd_document.Document(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].document == gcd_document.Document(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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']), - ) - - -def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): - 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_from_dict(): - test_reload_document(request_type=dict) - - -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] - assert args[0].name == 'name_value' - assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') - - -def test_reload_document_flattened_error(): - client = DocumentsClient( - credentials=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] - assert args[0].name == 'name_value' - assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') - - -@pytest.mark.asyncio -async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient( - credentials=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'), - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_documents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_documents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_documents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_documents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DocumentsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_documents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_documents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_documents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_documents_host_no_port(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_documents_host_with_port(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 ea5e97a3e..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py +++ /dev/null @@ -1,3580 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesAsyncClient -from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesClient -from google.cloud.dialogflow_v2beta1.services.entity_types import pagers -from google.cloud.dialogflow_v2beta1.services.entity_types import transports -from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - EntityTypesClient, - EntityTypesAsyncClient, -]) -def test_entity_types_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - EntityTypesClient, - EntityTypesAsyncClient, -]) -def test_entity_types_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_entity_types_client_get_transport_class(): - transport = EntityTypesClient.get_transport_class() - available_transports = [ - transports.EntityTypesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): - 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_from_dict(): - test_list_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) - -def test_list_entity_types_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): - 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_from_dict(): - test_get_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): - 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_from_dict(): - test_create_entity_type(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -def test_create_entity_type_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): - 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_from_dict(): - test_update_entity_type(request_type=dict) - - -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 = 'entity_type.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=entity_type.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 = 'entity_type.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=entity_type.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] - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].entity_type == gcd_entity_type.EntityType(name='name_value') - assert args[0].language_code == 'language_code_value' - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@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']), - ) - - -def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): - 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_from_dict(): - test_delete_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): - 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_from_dict(): - test_batch_update_entity_types(request_type=dict) - - -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'] - - -def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): - 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_from_dict(): - test_batch_delete_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type_names == ['entity_type_names_value'] - - -def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_type_names == ['entity_type_names_value'] - - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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'], - ) - - -def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): - 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_from_dict(): - test_batch_create_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -def test_batch_create_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): - 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_from_dict(): - test_batch_update_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -def test_batch_update_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entities == [entity_type.EntityType.Entity(value='value_value')] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): - 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_from_dict(): - test_batch_delete_entities(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].entity_values == ['entity_values_value'] - assert args[0].language_code == 'language_code_value' - - -def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].entity_values == ['entity_values_value'] - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - credentials=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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EntityTypesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EntityTypesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_entity_types_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_entity_types_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_entity_types_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_entity_types_host_no_port(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_entity_types_host_with_port(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 b7098b932..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py +++ /dev/null @@ -1,2420 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.environments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.environments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import environment -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - EnvironmentsClient, - EnvironmentsAsyncClient, -]) -def test_environments_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - EnvironmentsClient, - EnvironmentsAsyncClient, -]) -def test_environments_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): - 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_from_dict(): - test_list_environments(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -def test_list_environments_flattened_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_environments( - environment.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.ListEnvironmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_environments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_environments_flattened_error_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_environments( - environment.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_pager(): - client = EnvironmentsClient( - credentials=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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) - -def test_list_environments_pages(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): - 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_from_dict(): - test_get_environment(request_type=dict) - - -def test_get_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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'] - - -def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -def test_create_environment_from_dict(): - test_create_environment(request_type=dict) - - -def test_create_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - client.create_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - )) - response = await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -@pytest.mark.asyncio -async def test_create_environment_async_from_dict(): - await test_create_environment_async(request_type=dict) - - -def test_create_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.CreateEnvironmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.CreateEnvironmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -def test_update_environment_from_dict(): - test_update_environment(request_type=dict) - - -def test_update_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - client.update_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - )) - response = await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.agent_version == 'agent_version_value' - assert response.state == environment.Environment.State.STOPPED - - -@pytest.mark.asyncio -async def test_update_environment_async_from_dict(): - await test_update_environment_async(request_type=dict) - - -def test_update_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.UpdateEnvironmentRequest() - - request.environment.name = 'environment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'environment.name=environment.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.UpdateEnvironmentRequest() - - request.environment.name = 'environment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'environment.name=environment.name/value', - ) in kw['metadata'] - - -def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_environment_from_dict(): - test_delete_environment(request_type=dict) - - -def test_delete_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - client.delete_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_environment_async_from_dict(): - await test_delete_environment_async(request_type=dict) - - -def test_delete_environment_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.DeleteEnvironmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = None - client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.DeleteEnvironmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - ) - response = client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetEnvironmentHistoryPager) - assert response.parent == 'parent_value' - assert response.next_page_token == 'next_page_token_value' - - -def test_get_environment_history_from_dict(): - test_get_environment_history(request_type=dict) - - -def test_get_environment_history_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - client.get_environment_history() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - -@pytest.mark.asyncio -async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - )) - response = await client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) - assert response.parent == 'parent_value' - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_get_environment_history_async_from_dict(): - await test_get_environment_history_async(request_type=dict) - - -def test_get_environment_history_field_headers(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.GetEnvironmentHistoryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - call.return_value = environment.EnvironmentHistory() - client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_environment_history_field_headers_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = environment.GetEnvironmentHistoryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) - await client.get_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_get_environment_history_pager(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.get_environment_history(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) - -def test_get_environment_history_pages(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - pages = list(client.get_environment_history(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_get_environment_history_async_pager(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - async_pager = await client.get_environment_history(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in responses) - -@pytest.mark.asyncio -async def test_get_environment_history_async_pages(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - next_page_token='abc', - ), - environment.EnvironmentHistory( - entries=[], - next_page_token='def', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - ], - next_page_token='ghi', - ), - environment.EnvironmentHistory( - entries=[ - environment.EnvironmentHistory.Entry(), - environment.EnvironmentHistory.Entry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.get_environment_history(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EnvironmentsGrpcTransport, - ) - -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_environments', - 'get_environment', - 'create_environment', - 'update_environment', - 'delete_environment', - 'get_environment_history', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_environments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_environments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_environments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_environments_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_environments_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_environments_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_environments_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_environments_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_environments_host_no_port(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_environments_host_with_port(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - 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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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_withDEFAULT_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) 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 4ce1b74ae..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py +++ /dev/null @@ -1,3100 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.intents import IntentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.intents import IntentsClient -from google.cloud.dialogflow_v2beta1.services.intents import pagers -from google.cloud.dialogflow_v2beta1.services.intents import transports -from google.cloud.dialogflow_v2beta1.services.intents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.intents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import intent -from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - IntentsClient, - IntentsAsyncClient, -]) -def test_intents_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - IntentsClient, - IntentsAsyncClient, -]) -def test_intents_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_intents_client_get_transport_class(): - transport = IntentsClient.get_transport_class() - available_transports = [ - transports.IntentsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): - 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_from_dict(): - test_list_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].parent == 'parent_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) - -def test_list_intents_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): - 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_from_dict(): - test_get_intent(request_type=dict) - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -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] - assert args[0].name == 'name_value' - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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', - ) - - -def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): - 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_from_dict(): - test_create_intent(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - - -def test_create_intent_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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', - ) - - -def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): - 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_from_dict(): - test_update_intent(request_type=dict) - - -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 = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = gcd_intent.Intent() - client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=intent.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 = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - 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=intent.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] - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - assert args[0].language_code == 'language_code_value' - - -def test_update_intent_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].intent == gcd_intent.Intent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - assert args[0].language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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', - ) - - -def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): - 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_from_dict(): - test_delete_intent(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): - 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_from_dict(): - test_batch_update_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - - -def test_batch_update_intents_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - 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')]), - ) - - -def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): - 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_from_dict(): - test_batch_delete_intents(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].intents == [intent.Intent(name='name_value')] - - -def test_batch_delete_intents_flattened_error(): - client = IntentsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].intents == [intent.Intent(name='name_value')] - - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient( - credentials=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')], - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_intents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_intents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_intents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - IntentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - IntentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_intents_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_intents_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_intents_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_intents_host_no_port(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_intents_host_with_port(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 114d5265f..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py +++ /dev/null @@ -1,2378 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.knowledge_bases.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - KnowledgeBasesClient, - KnowledgeBasesAsyncClient, -]) -def test_knowledge_bases_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - KnowledgeBasesClient, - KnowledgeBasesAsyncClient, -]) -def test_knowledge_bases_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_knowledge_bases_client_get_transport_class(): - transport = KnowledgeBasesClient.get_transport_class() - available_transports = [ - transports.KnowledgeBasesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): - 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_from_dict(): - test_list_knowledge_bases(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) - -def test_list_knowledge_bases_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): - 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_from_dict(): - test_get_knowledge_base(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - 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_from_dict(): - test_create_knowledge_base(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - - -def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - - -@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'), - ) - - -def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - 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_from_dict(): - test_delete_knowledge_base(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - 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_from_dict(): - test_update_knowledge_base(request_type=dict) - - -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 = 'knowledge_base.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=knowledge_base.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 = 'knowledge_base.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=knowledge_base.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] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - credentials=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']), - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KnowledgeBasesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KnowledgeBasesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_knowledge_bases_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_knowledge_bases_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_knowledge_bases_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_knowledge_bases_host_no_port(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_knowledge_bases_host_with_port(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 99ad36723..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py +++ /dev/null @@ -1,3710 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.participants.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.participants.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import agent -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import context -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.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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", [ - ParticipantsClient, - ParticipantsAsyncClient, -]) -def test_participants_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - ParticipantsClient, - ParticipantsAsyncClient, -]) -def test_participants_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_participants_client_get_transport_class(): - transport = ParticipantsClient.get_transport_class() - available_transports = [ - transports.ParticipantsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): - 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_from_dict(): - test_create_participant(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].participant == gcd_participant.Participant(name='name_value') - - -def test_create_participant_flattened_error(): - client = ParticipantsClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].participant == gcd_participant.Participant(name='name_value') - - -@pytest.mark.asyncio -async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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'), - ) - - -def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): - 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_from_dict(): - test_get_participant(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): - 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_from_dict(): - test_list_participants(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) - -def test_list_participants_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_update_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): - 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_from_dict(): - test_update_participant(request_type=dict) - - -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 = 'participant.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=participant.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 = 'participant.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=participant.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] - assert args[0].participant == gcd_participant.Participant(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].participant == gcd_participant.Participant(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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']), - ) - - -def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): - 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_from_dict(): - test_analyze_content(request_type=dict) - - -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] - assert args[0].participant == 'participant_value' - assert args[0].event_input == session.EventInput(name='name_value') - - -def test_analyze_content_flattened_error(): - client = ParticipantsClient( - credentials=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] - assert args[0].participant == 'participant_value' - assert args[0].event_input == session.EventInput(name='name_value') - - -@pytest.mark.asyncio -async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient( - credentials=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'), - ) - - -def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): - 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_from_dict(): - test_suggest_articles(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): - 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_from_dict(): - test_suggest_faq_answers(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_suggest_smart_replies(transport: str = 'grpc', request_type=participant.SuggestSmartRepliesRequest): - 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_from_dict(): - test_suggest_smart_replies(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_list_suggestions(transport: str = 'grpc', request_type=participant.ListSuggestionsRequest): - 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_from_dict(): - test_list_suggestions(request_type=dict) - - -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(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_suggestions), - '__call__') as call: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, participant.Suggestion) - for i in results) - -def test_list_suggestions_pages(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_suggestions), - '__call__') as call: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_compile_suggestion(transport: str = 'grpc', request_type=participant.CompileSuggestionRequest): - 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_from_dict(): - test_compile_suggestion(request_type=dict) - - -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'] - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - 'suggest_articles', - 'suggest_faq_answers', - 'suggest_smart_replies', - 'list_suggestions', - 'compile_suggestion', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_participants_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParticipantsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_participants_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParticipantsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_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() - - -@requires_google_auth_gte_1_25_0 -def test_participants_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParticipantsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_participants_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParticipantsClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_participants_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_participants_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_participants_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_participants_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_participants_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_participants_host_no_port(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_participants_host_with_port(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - 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": "octopus", - "session": "oyster", - "context": "nudibranch", - } - 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 = "cuttlefish" - knowledge_base = "mussel" - document = "winkle" - 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": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", - } - 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 = "squid" - intent = "clam" - 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": "whelk", - "intent": "octopus", - } - 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 = "oyster" - conversation = "nudibranch" - message = "cuttlefish" - 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": "mussel", - "conversation": "winkle", - "message": "nautilus", - } - 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 = "scallop" - conversation = "abalone" - participant = "squid" - 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": "clam", - "conversation": "whelk", - "participant": "octopus", - } - 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 = "oyster" - session = "nudibranch" - entity_type = "cuttlefish" - 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": "mussel", - "session": "winkle", - "entity_type": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = ParticipantsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ParticipantsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = ParticipantsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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_withDEFAULT_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) 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 04a57bd5e..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py +++ /dev/null @@ -1,2369 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.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.services.session_entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - SessionEntityTypesClient, - SessionEntityTypesAsyncClient, -]) -def test_session_entity_types_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SessionEntityTypesClient, - SessionEntityTypesAsyncClient, -]) -def test_session_entity_types_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_session_entity_types_client_get_transport_class(): - transport = SessionEntityTypesClient.get_transport_class() - available_transports = [ - transports.SessionEntityTypesGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): - 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_from_dict(): - test_list_session_entity_types(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) - -def test_list_session_entity_types_pages(): - 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: - # 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: - 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: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): - 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_from_dict(): - test_get_session_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - 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_from_dict(): - test_create_session_entity_type(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - - -def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - credentials=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] - assert args[0].parent == 'parent_value' - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - - -@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'), - ) - - -def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - 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_from_dict(): - test_update_session_entity_type(request_type=dict) - - -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 = 'session_entity_type.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=session_entity_type.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 = 'session_entity_type.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=session_entity_type.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] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -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] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - credentials=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']), - ) - - -def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - 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_from_dict(): - test_delete_session_entity_type(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_session_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionEntityTypesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionEntityTypesClient() - adc.assert_called_once_with( - scopes=( '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, - ], -) -@requires_google_auth_gte_1_25_0 -def test_session_entity_types_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_session_entity_types_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_session_entity_types_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_session_entity_types_host_no_port(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_session_entity_types_host_with_port(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) 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 835506f4a..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py +++ /dev/null @@ -1,1403 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.sessions import SessionsAsyncClient -from google.cloud.dialogflow_v2beta1.services.sessions import SessionsClient -from google.cloud.dialogflow_v2beta1.services.sessions import transports -from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflow_v2beta1.types import agent -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import context -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.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 - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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", [ - SessionsClient, - SessionsAsyncClient, -]) -def test_sessions_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SessionsClient, - SessionsAsyncClient, -]) -def test_sessions_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_sessions_client_get_transport_class(): - transport = SessionsClient.get_transport_class() - available_transports = [ - transports.SessionsGrpcTransport, - ] - 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"), -]) -@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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_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, - ) - - -def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): - 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_from_dict(): - test_detect_intent(request_type=dict) - - -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] - assert args[0].session == 'session_value' - assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - - -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] - assert args[0].session == 'session_value' - assert args[0].query_input == gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - - -@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)), - ) - - -def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): - 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) - - -def test_streaming_detect_intent_from_dict(): - test_streaming_detect_intent(request_type=dict) - - -@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) - - -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 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_sessions_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_sessions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('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() - - -@requires_google_auth_gte_1_25_0 -def test_sessions_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SessionsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_sessions_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_sessions_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_sessions_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_sessions_host_no_port(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_sessions_host_with_port(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' - -def test_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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_withDEFAULT_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) diff --git a/scripts/fixup_dialogflow_v2_keywords.py b/scripts/fixup_dialogflow_v2_keywords.py index a6f9a0f0c..cc0f68eb9 100644 --- a/scripts/fixup_dialogflow_v2_keywords.py +++ b/scripts/fixup_dialogflow_v2_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,77 +39,88 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'reload_document': ('name', 'content_uri', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'content_uri', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -142,7 +151,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_dialogflow_v2beta1_keywords.py b/scripts/fixup_dialogflow_v2beta1_keywords.py index edac9dea1..0a8e20f0b 100644 --- a/scripts/fixup_dialogflow_v2beta1_keywords.py +++ b/scripts/fixup_dialogflow_v2beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,83 +39,94 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_create_messages': ('parent', 'requests', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_answer_record': ('name', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), - 'list_answer_records': ('parent', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), - 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_create_messages': ('parent', 'requests', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_answer_record': ('name', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), + 'list_answer_records': ('parent', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -148,7 +157,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py b/tests/__init__.py similarity index 100% rename from owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py rename to tests/__init__.py diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py b/tests/unit/__init__.py similarity index 100% rename from owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py rename to tests/unit/__init__.py diff --git a/owl-bot-staging/v2/tests/__init__.py b/tests/unit/gapic/__init__.py similarity index 99% rename from owl-bot-staging/v2/tests/__init__.py rename to tests/unit/gapic/__init__.py index b54a5fcc4..4de65971c 100644 --- a/owl-bot-staging/v2/tests/__init__.py +++ b/tests/unit/gapic/__init__.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # diff --git a/tests/unit/gapic/dialogflow_v2/__init__.py b/tests/unit/gapic/dialogflow_v2/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/dialogflow_v2/__init__.py +++ b/tests/unit/gapic/dialogflow_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/dialogflow_v2/test_agents.py b/tests/unit/gapic/dialogflow_v2/test_agents.py index 12e3d6800..95acf4713 100644 --- a/tests/unit/gapic/dialogflow_v2/test_agents.py +++ b/tests/unit/gapic/dialogflow_v2/test_agents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,56 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.agents import AgentsAsyncClient from google.cloud.dialogflow_v2.services.agents import AgentsClient from google.cloud.dialogflow_v2.services.agents import pagers from google.cloud.dialogflow_v2.services.agents import transports +from google.cloud.dialogflow_v2.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +115,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +130,7 @@ def test_agents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +173,7 @@ def test_agents_client_get_transport_class(): def test_agents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(AgentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +445,7 @@ def test_agents_client_client_options_from_dict(): def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -442,41 +469,26 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): api_version=agent.Agent.ApiVersion.API_VERSION_V1, tier=agent.Agent.Tier.TIER_STANDARD, ) - response = client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -488,7 +500,7 @@ def test_get_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -496,7 +508,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -505,7 +516,7 @@ async def test_get_agent_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -531,40 +542,26 @@ async def test_get_agent_async( tier=agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -574,17 +571,17 @@ async def test_get_agent_async_from_dict(): def test_get_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = agent.Agent() - client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -599,17 +596,17 @@ def test_get_agent_field_headers(): @pytest.mark.asyncio async def test_get_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -623,13 +620,12 @@ async def test_get_agent_field_headers_async(): def test_get_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent(parent="parent_value",) @@ -638,12 +634,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_get_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -655,7 +650,7 @@ def test_get_agent_flattened_error(): @pytest.mark.asyncio async def test_get_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: @@ -671,13 +666,12 @@ async def test_get_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_get_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -689,7 +683,7 @@ async def test_get_agent_flattened_error_async(): def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -713,41 +707,26 @@ def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentReque api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) - response = client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -759,7 +738,7 @@ def test_set_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -767,7 +746,6 @@ def test_set_agent_empty_call(): client.set_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() @@ -776,7 +754,7 @@ async def test_set_agent_async( transport: str = "grpc_asyncio", request_type=gcd_agent.SetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,40 +780,26 @@ async def test_set_agent_async( tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -845,17 +809,17 @@ async def test_set_agent_async_from_dict(): def test_set_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = gcd_agent.Agent() - client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +836,17 @@ def test_set_agent_field_headers(): @pytest.mark.asyncio async def test_set_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -898,13 +862,12 @@ async def test_set_agent_field_headers_async(): def test_set_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_agent(agent=gcd_agent.Agent(parent="parent_value"),) @@ -913,12 +876,11 @@ def test_set_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") def test_set_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -930,7 +892,7 @@ def test_set_agent_flattened_error(): @pytest.mark.asyncio async def test_set_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: @@ -946,13 +908,12 @@ async def test_set_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") @pytest.mark.asyncio async def test_set_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -964,7 +925,7 @@ async def test_set_agent_flattened_error_async(): def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -975,13 +936,11 @@ def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentReq with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -996,7 +955,7 @@ def test_delete_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1004,7 +963,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1013,7 +971,7 @@ async def test_delete_agent_async( transport: str = "grpc_asyncio", request_type=agent.DeleteAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1024,13 +982,11 @@ async def test_delete_agent_async( with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1043,17 +999,17 @@ async def test_delete_agent_async_from_dict(): def test_delete_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.DeleteAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = None - client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1068,17 +1024,17 @@ def test_delete_agent_field_headers(): @pytest.mark.asyncio async def test_delete_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.DeleteAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1092,13 +1048,12 @@ async def test_delete_agent_field_headers_async(): def test_delete_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_agent(parent="parent_value",) @@ -1107,12 +1062,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1124,7 +1078,7 @@ def test_delete_agent_flattened_error(): @pytest.mark.asyncio async def test_delete_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: @@ -1140,13 +1094,12 @@ async def test_delete_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1158,7 +1111,7 @@ async def test_delete_agent_flattened_error_async(): def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1171,19 +1124,15 @@ def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsR call.return_value = agent.SearchAgentsResponse( next_page_token="next_page_token_value", ) - response = client.search_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -1195,7 +1144,7 @@ def test_search_agents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1203,7 +1152,6 @@ def test_search_agents_empty_call(): client.search_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() @@ -1212,7 +1160,7 @@ async def test_search_agents_async( transport: str = "grpc_asyncio", request_type=agent.SearchAgentsRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1225,18 +1173,15 @@ async def test_search_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.search_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1246,17 +1191,17 @@ async def test_search_agents_async_from_dict(): def test_search_agents_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: call.return_value = agent.SearchAgentsResponse() - client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1271,11 +1216,12 @@ def test_search_agents_field_headers(): @pytest.mark.asyncio async def test_search_agents_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1229,6 @@ async def test_search_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse() ) - await client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1297,13 +1242,12 @@ async def test_search_agents_field_headers_async(): def test_search_agents_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.SearchAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_agents(parent="parent_value",) @@ -1312,12 +1256,11 @@ def test_search_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_search_agents_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1329,7 +1272,7 @@ def test_search_agents_flattened_error(): @pytest.mark.asyncio async def test_search_agents_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1347,13 +1290,12 @@ async def test_search_agents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_search_agents_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1364,7 +1306,7 @@ async def test_search_agents_flattened_error_async(): def test_search_agents_pager(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1394,7 +1336,7 @@ def test_search_agents_pager(): def test_search_agents_pages(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1416,7 +1358,7 @@ def test_search_agents_pages(): @pytest.mark.asyncio async def test_search_agents_async_pager(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1445,7 +1387,7 @@ async def test_search_agents_async_pager(): @pytest.mark.asyncio async def test_search_agents_async_pages(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1471,7 +1413,7 @@ async def test_search_agents_async_pages(): def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1482,13 +1424,11 @@ def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentReque with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1503,7 +1443,7 @@ def test_train_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1511,7 +1451,6 @@ def test_train_agent_empty_call(): client.train_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() @@ -1520,7 +1459,7 @@ async def test_train_agent_async( transport: str = "grpc_asyncio", request_type=agent.TrainAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1533,13 +1472,11 @@ async def test_train_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1552,17 +1489,17 @@ async def test_train_agent_async_from_dict(): def test_train_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1577,11 +1514,12 @@ def test_train_agent_field_headers(): @pytest.mark.asyncio async def test_train_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1527,6 @@ async def test_train_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1603,13 +1540,12 @@ async def test_train_agent_field_headers_async(): def test_train_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.train_agent(parent="parent_value",) @@ -1618,12 +1554,11 @@ def test_train_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_train_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1635,7 +1570,7 @@ def test_train_agent_flattened_error(): @pytest.mark.asyncio async def test_train_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: @@ -1653,13 +1588,12 @@ async def test_train_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_train_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1671,7 +1605,7 @@ async def test_train_agent_flattened_error_async(): def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1682,13 +1616,11 @@ def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentReq with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1703,7 +1635,7 @@ def test_export_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1711,7 +1643,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1720,7 +1651,7 @@ async def test_export_agent_async( transport: str = "grpc_asyncio", request_type=agent.ExportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1733,13 +1664,11 @@ async def test_export_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1752,17 +1681,17 @@ async def test_export_agent_async_from_dict(): def test_export_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ExportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1777,11 +1706,12 @@ def test_export_agent_field_headers(): @pytest.mark.asyncio async def test_export_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ExportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1789,7 +1719,6 @@ async def test_export_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1803,13 +1732,12 @@ async def test_export_agent_field_headers_async(): def test_export_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.export_agent(parent="parent_value",) @@ -1818,12 +1746,11 @@ def test_export_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_export_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1835,7 +1762,7 @@ def test_export_agent_flattened_error(): @pytest.mark.asyncio async def test_export_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: @@ -1853,13 +1780,12 @@ async def test_export_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_export_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1871,7 +1797,7 @@ async def test_export_agent_flattened_error_async(): def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1882,13 +1808,11 @@ def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentReq with mock.patch.object(type(client.transport.import_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1903,7 +1827,7 @@ def test_import_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1911,7 +1835,6 @@ def test_import_agent_empty_call(): client.import_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() @@ -1920,7 +1843,7 @@ async def test_import_agent_async( transport: str = "grpc_asyncio", request_type=agent.ImportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1933,13 +1856,11 @@ async def test_import_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1952,17 +1873,17 @@ async def test_import_agent_async_from_dict(): def test_import_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1977,11 +1898,12 @@ def test_import_agent_field_headers(): @pytest.mark.asyncio async def test_import_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1911,6 @@ async def test_import_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2004,7 +1925,7 @@ async def test_import_agent_field_headers_async(): def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2015,13 +1936,11 @@ def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentR with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -2036,7 +1955,7 @@ def test_restore_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1963,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -2053,7 +1971,7 @@ async def test_restore_agent_async( transport: str = "grpc_asyncio", request_type=agent.RestoreAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2066,13 +1984,11 @@ async def test_restore_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -2085,17 +2001,17 @@ async def test_restore_agent_async_from_dict(): def test_restore_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.RestoreAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2110,11 +2026,12 @@ def test_restore_agent_field_headers(): @pytest.mark.asyncio async def test_restore_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.RestoreAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2122,7 +2039,6 @@ async def test_restore_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2139,7 +2055,7 @@ def test_get_validation_result( transport: str = "grpc", request_type=agent.GetValidationResultRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2152,17 +2068,14 @@ def test_get_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = validation_result.ValidationResult() - response = client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) @@ -2174,7 +2087,7 @@ def test_get_validation_result_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2184,7 +2097,6 @@ def test_get_validation_result_empty_call(): client.get_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() @@ -2193,7 +2105,7 @@ async def test_get_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetValidationResultRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2208,13 +2120,11 @@ async def test_get_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - response = await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() # Establish that the response is the type that we expect. @@ -2227,11 +2137,12 @@ async def test_get_validation_result_async_from_dict(): def test_get_validation_result_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2239,7 +2150,6 @@ def test_get_validation_result_field_headers(): type(client.transport.get_validation_result), "__call__" ) as call: call.return_value = validation_result.ValidationResult() - client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2254,11 +2164,12 @@ def test_get_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_validation_result_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2268,7 +2179,6 @@ async def test_get_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2284,16 +2194,16 @@ async def test_get_validation_result_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2303,7 +2213,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2314,7 +2224,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AgentsClient(transport=transport) assert client.transport is transport @@ -2323,13 +2233,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AgentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2341,23 +2251,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AgentsGrpcTransport,) def test_agents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2369,7 +2279,7 @@ def test_agents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2395,15 +2305,40 @@ def test_agents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_agents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2419,19 +2354,36 @@ def test_agents_base_transport_with_credentials_file(): def test_agents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_agents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AgentsClient() adc.assert_called_once_with( scopes=( @@ -2442,14 +2394,38 @@ def test_agents_auth_adc(): ) -def test_agents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_agents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AgentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_agents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2459,12 +2435,123 @@ def test_agents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport], ) def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2506,7 +2593,7 @@ def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_agents_host_no_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2516,7 +2603,7 @@ def test_agents_host_no_port(): def test_agents_host_with_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2567,9 +2654,9 @@ def test_agents_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2648,7 +2735,7 @@ def test_agents_transport_channel_mtls_with_adc(transport_class): def test_agents_grpc_lro_client(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2661,7 +2748,7 @@ def test_agents_grpc_lro_client(): def test_agents_grpc_lro_async_client(): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2674,7 +2761,6 @@ def test_agents_grpc_lro_async_client(): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = AgentsClient.agent_path(project) assert expected == actual @@ -2693,7 +2779,6 @@ def test_parse_agent_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2714,7 +2799,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2733,7 +2817,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2752,7 +2835,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2772,7 +2854,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2799,7 +2880,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AgentsTransport, "_prep_wrapped_messages" ) as prep: client = AgentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2808,6 +2889,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AgentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_answer_records.py b/tests/unit/gapic/dialogflow_v2/test_answer_records.py index 39c5932a3..ac47c90bd 100644 --- a/tests/unit/gapic/dialogflow_v2/test_answer_records.py +++ b/tests/unit/gapic/dialogflow_v2/test_answer_records.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,24 +23,54 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsAsyncClient from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsClient from google.cloud.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.services.answer_records import transports +from google.cloud.dialogflow_v2.services.answer_records.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.answer_records.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record from google.cloud.dialogflow_v2.types import participant from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -109,7 +138,7 @@ def test_answer_records_client_from_service_account_info(client_class): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -162,7 +191,7 @@ def test_answer_records_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AnswerRecordsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -450,7 +479,7 @@ def test_list_answer_records( transport: str = "grpc", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,19 +494,15 @@ def test_list_answer_records( call.return_value = answer_record.ListAnswerRecordsResponse( next_page_token="next_page_token_value", ) - response = client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == "next_page_token_value" @@ -489,7 +514,7 @@ def test_list_answer_records_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -499,7 +524,6 @@ def test_list_answer_records_empty_call(): client.list_answer_records() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() @@ -508,7 +532,7 @@ async def test_list_answer_records_async( transport: str = "grpc_asyncio", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -525,18 +549,15 @@ async def test_list_answer_records_async( next_page_token="next_page_token_value", ) ) - response = await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -546,11 +567,12 @@ async def test_list_answer_records_async_from_dict(): def test_list_answer_records_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -558,7 +580,6 @@ def test_list_answer_records_field_headers(): type(client.transport.list_answer_records), "__call__" ) as call: call.return_value = answer_record.ListAnswerRecordsResponse() - client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -573,11 +594,14 @@ def test_list_answer_records_field_headers(): @pytest.mark.asyncio async def test_list_answer_records_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -587,7 +611,6 @@ async def test_list_answer_records_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.ListAnswerRecordsResponse() ) - await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -601,7 +624,7 @@ async def test_list_answer_records_field_headers_async(): def test_list_answer_records_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -609,7 +632,6 @@ def test_list_answer_records_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = answer_record.ListAnswerRecordsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_answer_records(parent="parent_value",) @@ -618,12 +640,11 @@ def test_list_answer_records_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -635,7 +656,9 @@ def test_list_answer_records_flattened_error(): @pytest.mark.asyncio async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -655,13 +678,14 @@ async def test_list_answer_records_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -672,7 +696,7 @@ async def test_list_answer_records_flattened_error_async(): def test_list_answer_records_pager(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -717,7 +741,7 @@ def test_list_answer_records_pager(): def test_list_answer_records_pages(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -754,7 +778,7 @@ def test_list_answer_records_pages(): @pytest.mark.asyncio async def test_list_answer_records_async_pager(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -798,7 +822,7 @@ async def test_list_answer_records_async_pager(): @pytest.mark.asyncio async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -841,7 +865,7 @@ def test_update_answer_record( transport: str = "grpc", request_type=gcd_answer_record.UpdateAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -859,19 +883,15 @@ def test_update_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -883,7 +903,7 @@ def test_update_answer_record_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -893,7 +913,6 @@ def test_update_answer_record_empty_call(): client.update_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() @@ -903,7 +922,7 @@ async def test_update_answer_record_async( request_type=gcd_answer_record.UpdateAnswerRecordRequest, ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -918,18 +937,15 @@ async def test_update_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord(name="name_value",) ) - response = await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -939,11 +955,12 @@ async def test_update_answer_record_async_from_dict(): def test_update_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -951,7 +968,6 @@ def test_update_answer_record_field_headers(): type(client.transport.update_answer_record), "__call__" ) as call: call.return_value = gcd_answer_record.AnswerRecord() - client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -969,11 +985,14 @@ def test_update_answer_record_field_headers(): @pytest.mark.asyncio async def test_update_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -983,7 +1002,6 @@ async def test_update_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord() ) - await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1000,7 +1018,7 @@ async def test_update_answer_record_field_headers_async(): def test_update_answer_record_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1008,28 +1026,25 @@ def test_update_answer_record_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_answer_record.AnswerRecord() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].answer_record == gcd_answer_record.AnswerRecord( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_answer_record_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1037,13 +1052,15 @@ def test_update_answer_record_flattened_error(): client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1059,24 +1076,24 @@ async def test_update_answer_record_flattened_async(): # using the keyword arguments to the method. response = await client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].answer_record == gcd_answer_record.AnswerRecord( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1084,23 +1101,23 @@ async def test_update_answer_record_flattened_error_async(): await client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1110,7 +1127,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1121,7 +1138,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AnswerRecordsClient(transport=transport) assert client.transport is transport @@ -1130,13 +1147,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1151,23 +1168,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AnswerRecordsGrpcTransport,) def test_answer_records_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1179,7 +1196,7 @@ def test_answer_records_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1193,15 +1210,40 @@ def test_answer_records_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_answer_records_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1217,19 +1259,36 @@ def test_answer_records_base_transport_with_credentials_file(): def test_answer_records_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_answer_records_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AnswerRecordsClient() adc.assert_called_once_with( scopes=( @@ -1240,14 +1299,44 @@ def test_answer_records_auth_adc(): ) -def test_answer_records_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AnswerRecordsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1257,6 +1346,121 @@ def test_answer_records_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1265,7 +1469,7 @@ def test_answer_records_transport_auth_adc(): ], ) def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1307,7 +1511,7 @@ def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_cla def test_answer_records_host_no_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1317,7 +1521,7 @@ def test_answer_records_host_no_port(): def test_answer_records_host_with_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1371,9 +1575,9 @@ def test_answer_records_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1456,7 +1660,6 @@ def test_answer_records_transport_channel_mtls_with_adc(transport_class): def test_answer_record_path(): project = "squid" answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format( project=project, answer_record=answer_record, ) @@ -1478,7 +1681,6 @@ def test_parse_answer_record_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1499,7 +1701,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AnswerRecordsClient.common_folder_path(folder) assert expected == actual @@ -1518,7 +1719,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AnswerRecordsClient.common_organization_path(organization) assert expected == actual @@ -1537,7 +1737,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AnswerRecordsClient.common_project_path(project) assert expected == actual @@ -1557,7 +1756,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1584,7 +1782,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AnswerRecordsTransport, "_prep_wrapped_messages" ) as prep: client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1593,6 +1791,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AnswerRecordsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_contexts.py b/tests/unit/gapic/dialogflow_v2/test_contexts.py index 8d2548366..828a4171a 100644 --- a/tests/unit/gapic/dialogflow_v2/test_contexts.py +++ b/tests/unit/gapic/dialogflow_v2/test_contexts.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.contexts import ContextsAsyncClient from google.cloud.dialogflow_v2.services.contexts import ContextsClient from google.cloud.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.services.contexts import transports +from google.cloud.dialogflow_v2.services.contexts.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.contexts.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_contexts_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_contexts_client_get_transport_class(): def test_contexts_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(ContextsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -420,7 +449,7 @@ def test_list_contexts( transport: str = "grpc", request_type=context.ListContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -433,19 +462,15 @@ def test_list_contexts( call.return_value = context.ListContextsResponse( next_page_token="next_page_token_value", ) - response = client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_contexts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -465,7 +490,6 @@ def test_list_contexts_empty_call(): client.list_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() @@ -474,7 +498,7 @@ async def test_list_contexts_async( transport: str = "grpc_asyncio", request_type=context.ListContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -487,18 +511,15 @@ async def test_list_contexts_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContextsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_contexts_async_from_dict(): def test_list_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: call.return_value = context.ListContextsResponse() - client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_contexts_field_headers(): @pytest.mark.asyncio async def test_list_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_contexts_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse() ) - await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_contexts_field_headers_async(): def test_list_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.ListContextsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_contexts(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -591,7 +610,7 @@ def test_list_contexts_flattened_error(): @pytest.mark.asyncio async def test_list_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_contexts_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -626,7 +644,7 @@ async def test_list_contexts_flattened_error_async(): def test_list_contexts_pager(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_contexts_pager(): def test_list_contexts_pages(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_contexts_pages(): @pytest.mark.asyncio async def test_list_contexts_async_pager(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +737,7 @@ async def test_list_contexts_async_pager(): @pytest.mark.asyncio async def test_list_contexts_async_pages(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -749,7 +767,7 @@ async def test_list_contexts_async_pages(): def test_get_context(transport: str = "grpc", request_type=context.GetContextRequest): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -760,21 +778,16 @@ def test_get_context(transport: str = "grpc", request_type=context.GetContextReq with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context(name="name_value", lifespan_count=1498,) - response = client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -786,7 +799,7 @@ def test_get_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -794,7 +807,6 @@ def test_get_context_empty_call(): client.get_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() @@ -803,7 +815,7 @@ async def test_get_context_async( transport: str = "grpc_asyncio", request_type=context.GetContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -816,20 +828,16 @@ async def test_get_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -839,17 +847,17 @@ async def test_get_context_async_from_dict(): def test_get_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = context.Context() - client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -864,17 +872,17 @@ def test_get_context_field_headers(): @pytest.mark.asyncio async def test_get_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - await client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -888,13 +896,12 @@ async def test_get_context_field_headers_async(): def test_get_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_context(name="name_value",) @@ -903,12 +910,11 @@ def test_get_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +926,7 @@ def test_get_context_flattened_error(): @pytest.mark.asyncio async def test_get_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: @@ -936,13 +942,12 @@ async def test_get_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +961,7 @@ def test_create_context( transport: str = "grpc", request_type=gcd_context.CreateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,21 +972,16 @@ def test_create_context( with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -993,7 +993,7 @@ def test_create_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +1001,6 @@ def test_create_context_empty_call(): client.create_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() @@ -1010,7 +1009,7 @@ async def test_create_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.CreateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1023,20 +1022,16 @@ async def test_create_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1046,17 +1041,17 @@ async def test_create_context_async_from_dict(): def test_create_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = gcd_context.Context() - client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1071,17 +1066,17 @@ def test_create_context_field_headers(): @pytest.mark.asyncio async def test_create_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1095,13 +1090,12 @@ async def test_create_context_field_headers_async(): def test_create_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_context( @@ -1112,14 +1106,12 @@ def test_create_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") def test_create_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1133,7 +1125,7 @@ def test_create_context_flattened_error(): @pytest.mark.asyncio async def test_create_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: @@ -1151,15 +1143,13 @@ async def test_create_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") @pytest.mark.asyncio async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,7 +1165,7 @@ def test_update_context( transport: str = "grpc", request_type=gcd_context.UpdateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1186,21 +1176,16 @@ def test_update_context( with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1212,7 +1197,7 @@ def test_update_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1205,6 @@ def test_update_context_empty_call(): client.update_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() @@ -1229,7 +1213,7 @@ async def test_update_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.UpdateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,20 +1226,16 @@ async def test_update_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1265,17 +1245,17 @@ async def test_update_context_async_from_dict(): def test_update_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = gcd_context.Context() - client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1292,17 +1272,17 @@ def test_update_context_field_headers(): @pytest.mark.asyncio async def test_update_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1318,32 +1298,29 @@ async def test_update_context_field_headers_async(): def test_update_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_context( context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].context == gcd_context.Context(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1351,13 +1328,13 @@ def test_update_context_flattened_error(): client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: @@ -1369,22 +1346,20 @@ async def test_update_context_flattened_async(): # using the keyword arguments to the method. response = await client.update_context( context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].context == gcd_context.Context(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1392,7 +1367,7 @@ async def test_update_context_flattened_error_async(): await client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1400,7 +1375,7 @@ def test_delete_context( transport: str = "grpc", request_type=context.DeleteContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1411,13 +1386,11 @@ def test_delete_context( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1432,7 +1405,7 @@ def test_delete_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1440,7 +1413,6 @@ def test_delete_context_empty_call(): client.delete_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() @@ -1449,7 +1421,7 @@ async def test_delete_context_async( transport: str = "grpc_asyncio", request_type=context.DeleteContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1460,13 +1432,11 @@ async def test_delete_context_async( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1479,17 +1449,17 @@ async def test_delete_context_async_from_dict(): def test_delete_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = None - client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1504,17 +1474,17 @@ def test_delete_context_field_headers(): @pytest.mark.asyncio async def test_delete_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1528,13 +1498,12 @@ async def test_delete_context_field_headers_async(): def test_delete_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_context(name="name_value",) @@ -1543,12 +1512,11 @@ def test_delete_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1560,7 +1528,7 @@ def test_delete_context_flattened_error(): @pytest.mark.asyncio async def test_delete_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: @@ -1576,13 +1544,12 @@ async def test_delete_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,7 +1563,7 @@ def test_delete_all_contexts( transport: str = "grpc", request_type=context.DeleteAllContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1609,13 +1576,11 @@ def test_delete_all_contexts( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1630,7 +1595,7 @@ def test_delete_all_contexts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1640,7 +1605,6 @@ def test_delete_all_contexts_empty_call(): client.delete_all_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() @@ -1649,7 +1613,7 @@ async def test_delete_all_contexts_async( transport: str = "grpc_asyncio", request_type=context.DeleteAllContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1626,11 @@ async def test_delete_all_contexts_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1681,11 +1643,12 @@ async def test_delete_all_contexts_async_from_dict(): def test_delete_all_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1656,6 @@ def test_delete_all_contexts_field_headers(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = None - client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1670,12 @@ def test_delete_all_contexts_field_headers(): @pytest.mark.asyncio async def test_delete_all_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1683,6 @@ async def test_delete_all_contexts_field_headers_async(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1734,7 +1696,7 @@ async def test_delete_all_contexts_field_headers_async(): def test_delete_all_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1742,7 +1704,6 @@ def test_delete_all_contexts_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_all_contexts(parent="parent_value",) @@ -1751,12 +1712,11 @@ def test_delete_all_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_all_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1768,7 +1728,7 @@ def test_delete_all_contexts_flattened_error(): @pytest.mark.asyncio async def test_delete_all_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1786,13 +1746,12 @@ async def test_delete_all_contexts_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1805,16 +1764,16 @@ async def test_delete_all_contexts_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1824,7 +1783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1835,7 +1794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ContextsClient(transport=transport) assert client.transport is transport @@ -1844,13 +1803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ContextsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1862,23 +1821,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ContextsGrpcTransport,) def test_contexts_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1890,7 +1849,7 @@ def test_contexts_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1908,15 +1867,40 @@ def test_contexts_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_contexts_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1932,19 +1916,36 @@ def test_contexts_base_transport_with_credentials_file(): def test_contexts_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_contexts_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ContextsClient() adc.assert_called_once_with( scopes=( @@ -1955,14 +1956,38 @@ def test_contexts_auth_adc(): ) -def test_contexts_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ContextsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1972,12 +1997,123 @@ def test_contexts_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport], ) def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2019,7 +2155,7 @@ def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): def test_contexts_host_no_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2029,7 +2165,7 @@ def test_contexts_host_no_port(): def test_contexts_host_with_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2080,9 +2216,9 @@ def test_contexts_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2163,7 +2299,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2186,7 +2321,6 @@ def test_parse_context_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2207,7 +2341,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = ContextsClient.common_folder_path(folder) assert expected == actual @@ -2226,7 +2359,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = ContextsClient.common_organization_path(organization) assert expected == actual @@ -2245,7 +2377,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = ContextsClient.common_project_path(project) assert expected == actual @@ -2265,7 +2396,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2292,7 +2422,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ContextsTransport, "_prep_wrapped_messages" ) as prep: client = ContextsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2301,6 +2431,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ContextsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py b/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py index d4ef7e529..c07d5061c 100644 --- a/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py +++ b/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.conversation_profiles import ( ConversationProfilesAsyncClient, @@ -40,14 +39,44 @@ ) from google.cloud.dialogflow_v2.services.conversation_profiles import pagers from google.cloud.dialogflow_v2.services.conversation_profiles import transports +from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import conversation_profile from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -116,7 +145,7 @@ def test_conversation_profiles_client_from_service_account_info(client_class): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -173,7 +202,7 @@ def test_conversation_profiles_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationProfilesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -480,7 +509,7 @@ def test_list_conversation_profiles( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -495,19 +524,15 @@ def test_list_conversation_profiles( call.return_value = conversation_profile.ListConversationProfilesResponse( next_page_token="next_page_token_value", ) - response = client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == "next_page_token_value" @@ -519,7 +544,7 @@ def test_list_conversation_profiles_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -529,7 +554,6 @@ def test_list_conversation_profiles_empty_call(): client.list_conversation_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() @@ -539,7 +563,7 @@ async def test_list_conversation_profiles_async( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -556,18 +580,15 @@ async def test_list_conversation_profiles_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationProfilesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -577,11 +598,14 @@ async def test_list_conversation_profiles_async_from_dict(): def test_list_conversation_profiles_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -589,7 +613,6 @@ def test_list_conversation_profiles_field_headers(): type(client.transport.list_conversation_profiles), "__call__" ) as call: call.return_value = conversation_profile.ListConversationProfilesResponse() - client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -605,12 +628,13 @@ def test_list_conversation_profiles_field_headers(): @pytest.mark.asyncio async def test_list_conversation_profiles_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -620,7 +644,6 @@ async def test_list_conversation_profiles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ListConversationProfilesResponse() ) - await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -634,7 +657,9 @@ async def test_list_conversation_profiles_field_headers_async(): def test_list_conversation_profiles_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -642,7 +667,6 @@ def test_list_conversation_profiles_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ListConversationProfilesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversation_profiles(parent="parent_value",) @@ -651,12 +675,13 @@ def test_list_conversation_profiles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -670,7 +695,7 @@ def test_list_conversation_profiles_flattened_error(): @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,14 +716,13 @@ async def test_list_conversation_profiles_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -711,7 +735,9 @@ async def test_list_conversation_profiles_flattened_error_async(): def test_list_conversation_profiles_pager(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -759,7 +785,9 @@ def test_list_conversation_profiles_pager(): def test_list_conversation_profiles_pages(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -798,7 +826,7 @@ def test_list_conversation_profiles_pages(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pager(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -847,7 +875,7 @@ async def test_list_conversation_profiles_async_pager(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pages(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -893,7 +921,7 @@ def test_get_conversation_profile( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -910,23 +938,17 @@ def test_get_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -938,7 +960,7 @@ def test_get_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -948,7 +970,6 @@ def test_get_conversation_profile_empty_call(): client.get_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() @@ -958,7 +979,7 @@ async def test_get_conversation_profile_async( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -977,22 +998,17 @@ async def test_get_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1002,11 +1018,14 @@ async def test_get_conversation_profile_async_from_dict(): def test_get_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1014,7 +1033,6 @@ def test_get_conversation_profile_field_headers(): type(client.transport.get_conversation_profile), "__call__" ) as call: call.return_value = conversation_profile.ConversationProfile() - client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1030,12 +1048,13 @@ def test_get_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_get_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1045,7 +1064,6 @@ async def test_get_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ConversationProfile() ) - await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1059,7 +1077,9 @@ async def test_get_conversation_profile_field_headers_async(): def test_get_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1067,7 +1087,6 @@ def test_get_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation_profile(name="name_value",) @@ -1076,12 +1095,13 @@ def test_get_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1094,7 +1114,7 @@ def test_get_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1115,14 +1135,13 @@ async def test_get_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1138,7 +1157,7 @@ def test_create_conversation_profile( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1155,23 +1174,17 @@ def test_create_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1183,7 +1196,7 @@ def test_create_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1193,7 +1206,6 @@ def test_create_conversation_profile_empty_call(): client.create_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() @@ -1203,7 +1215,7 @@ async def test_create_conversation_profile_async( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,22 +1234,17 @@ async def test_create_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1247,11 +1254,14 @@ async def test_create_conversation_profile_async_from_dict(): def test_create_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1259,7 +1269,6 @@ def test_create_conversation_profile_field_headers(): type(client.transport.create_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1275,12 +1284,13 @@ def test_create_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_create_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1290,7 +1300,6 @@ async def test_create_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1304,7 +1313,9 @@ async def test_create_conversation_profile_field_headers_async(): def test_create_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1312,7 +1323,6 @@ def test_create_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation_profile( @@ -1326,9 +1336,7 @@ def test_create_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1337,7 +1345,9 @@ def test_create_conversation_profile_flattened(): def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1354,7 +1364,7 @@ def test_create_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1380,9 +1390,7 @@ async def test_create_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1393,7 +1401,7 @@ async def test_create_conversation_profile_flattened_async(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1413,7 +1421,7 @@ def test_update_conversation_profile( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1430,23 +1438,17 @@ def test_update_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1458,7 +1460,7 @@ def test_update_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1468,7 +1470,6 @@ def test_update_conversation_profile_empty_call(): client.update_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() @@ -1478,7 +1479,7 @@ async def test_update_conversation_profile_async( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1497,22 +1498,17 @@ async def test_update_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1522,11 +1518,14 @@ async def test_update_conversation_profile_async_from_dict(): def test_update_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1534,7 +1533,6 @@ def test_update_conversation_profile_field_headers(): type(client.transport.update_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1553,12 +1551,13 @@ def test_update_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_update_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1568,7 +1567,6 @@ async def test_update_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1585,7 +1583,9 @@ async def test_update_conversation_profile_field_headers_async(): def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1593,32 +1593,31 @@ def test_update_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_conversation_profile( conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1628,14 +1627,14 @@ def test_update_conversation_profile_flattened_error(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1654,27 +1653,25 @@ async def test_update_conversation_profile_flattened_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1685,7 +1682,7 @@ async def test_update_conversation_profile_flattened_error_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1694,7 +1691,7 @@ def test_delete_conversation_profile( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1707,13 +1704,11 @@ def test_delete_conversation_profile( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1728,7 +1723,7 @@ def test_delete_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1738,7 +1733,6 @@ def test_delete_conversation_profile_empty_call(): client.delete_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() @@ -1748,7 +1742,7 @@ async def test_delete_conversation_profile_async( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1761,13 +1755,11 @@ async def test_delete_conversation_profile_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1780,11 +1772,14 @@ async def test_delete_conversation_profile_async_from_dict(): def test_delete_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1792,7 +1787,6 @@ def test_delete_conversation_profile_field_headers(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = None - client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1808,12 +1802,13 @@ def test_delete_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_delete_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1821,7 +1816,6 @@ async def test_delete_conversation_profile_field_headers_async(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1835,7 +1829,9 @@ async def test_delete_conversation_profile_field_headers_async(): def test_delete_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1843,7 +1839,6 @@ def test_delete_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_conversation_profile(name="name_value",) @@ -1852,12 +1847,13 @@ def test_delete_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1870,7 +1866,7 @@ def test_delete_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1889,14 +1885,13 @@ async def test_delete_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1910,16 +1905,16 @@ async def test_delete_conversation_profile_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1929,7 +1924,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1940,7 +1935,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationProfilesClient(transport=transport) assert client.transport is transport @@ -1949,13 +1944,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1970,23 +1965,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.ConversationProfilesGrpcTransport,) def test_conversation_profiles_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1998,7 +1995,7 @@ def test_conversation_profiles_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2015,15 +2012,40 @@ def test_conversation_profiles_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2039,19 +2061,36 @@ def test_conversation_profiles_base_transport_with_credentials_file(): def test_conversation_profiles_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ConversationProfilesClient() adc.assert_called_once_with( scopes=( @@ -2062,14 +2101,44 @@ def test_conversation_profiles_auth_adc(): ) -def test_conversation_profiles_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ConversationProfilesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2079,6 +2148,121 @@ def test_conversation_profiles_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2089,7 +2273,7 @@ def test_conversation_profiles_transport_auth_adc(): def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2131,7 +2315,7 @@ def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( def test_conversation_profiles_host_no_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2141,7 +2325,7 @@ def test_conversation_profiles_host_no_port(): def test_conversation_profiles_host_with_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2197,9 +2381,9 @@ def test_conversation_profiles_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2281,7 +2465,6 @@ def test_conversation_profiles_transport_channel_mtls_with_adc(transport_class): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = ConversationProfilesClient.agent_path(project) assert expected == actual @@ -2298,10 +2481,35 @@ def test_parse_agent_path(): assert expected == actual -def test_conversation_profile_path(): +def test_conversation_model_path(): project = "whelk" - conversation_profile = "octopus" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + actual = ConversationProfilesClient.conversation_model_path( + project, location, conversation_model + ) + assert expected == actual + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2313,8 +2521,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "oyster", - "conversation_profile": "nudibranch", + "project": "scallop", + "conversation_profile": "abalone", } path = ConversationProfilesClient.conversation_profile_path(**expected) @@ -2324,10 +2532,9 @@ def test_parse_conversation_profile_path(): def test_document_path(): - project = "cuttlefish" - knowledge_base = "mussel" - document = "winkle" - + project = "squid" + knowledge_base = "clam" + document = "whelk" expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2337,9 +2544,9 @@ def test_document_path(): def test_parse_document_path(): expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", } path = ConversationProfilesClient.document_path(**expected) @@ -2349,9 +2556,8 @@ def test_parse_document_path(): def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - + project = "cuttlefish" + knowledge_base = "mussel" expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2361,8 +2567,8 @@ def test_knowledge_base_path(): def test_parse_knowledge_base_path(): expected = { - "project": "whelk", - "knowledge_base": "octopus", + "project": "winkle", + "knowledge_base": "nautilus", } path = ConversationProfilesClient.knowledge_base_path(**expected) @@ -2372,8 +2578,7 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): - billing_account = "oyster" - + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2383,7 +2588,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = ConversationProfilesClient.common_billing_account_path(**expected) @@ -2393,8 +2598,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "squid" expected = "folders/{folder}".format(folder=folder,) actual = ConversationProfilesClient.common_folder_path(folder) assert expected == actual @@ -2402,7 +2606,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = ConversationProfilesClient.common_folder_path(**expected) @@ -2412,8 +2616,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "whelk" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationProfilesClient.common_organization_path(organization) assert expected == actual @@ -2421,7 +2624,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = ConversationProfilesClient.common_organization_path(**expected) @@ -2431,8 +2634,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "oyster" expected = "projects/{project}".format(project=project,) actual = ConversationProfilesClient.common_project_path(project) assert expected == actual @@ -2440,7 +2642,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = ConversationProfilesClient.common_project_path(**expected) @@ -2450,9 +2652,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2462,8 +2663,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = ConversationProfilesClient.common_location_path(**expected) @@ -2479,7 +2680,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationProfilesTransport, "_prep_wrapped_messages" ) as prep: client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2488,6 +2689,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationProfilesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_conversations.py b/tests/unit/gapic/dialogflow_v2/test_conversations.py index 2f3f7b185..773ba97eb 100644 --- a/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2/test_conversations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.conversations import ConversationsAsyncClient from google.cloud.dialogflow_v2.services.conversations import ConversationsClient from google.cloud.dialogflow_v2.services.conversations import pagers from google.cloud.dialogflow_v2.services.conversations import transports +from google.cloud.dialogflow_v2.services.conversations.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.conversations.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -108,7 +137,7 @@ def test_conversations_client_from_service_account_info(client_class): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -161,7 +190,7 @@ def test_conversations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -449,7 +478,7 @@ def test_create_conversation( transport: str = "grpc", request_type=gcd_conversation.CreateConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -467,28 +496,21 @@ def test_create_conversation( conversation_profile="conversation_profile_value", conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -503,7 +525,7 @@ def test_create_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -513,7 +535,6 @@ def test_create_conversation_empty_call(): client.create_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() @@ -523,7 +544,7 @@ async def test_create_conversation_async( request_type=gcd_conversation.CreateConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,27 +564,21 @@ async def test_create_conversation_async( conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -576,11 +591,12 @@ async def test_create_conversation_async_from_dict(): def test_create_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +604,6 @@ def test_create_conversation_field_headers(): type(client.transport.create_conversation), "__call__" ) as call: call.return_value = gcd_conversation.Conversation() - client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -603,11 +618,14 @@ def test_create_conversation_field_headers(): @pytest.mark.asyncio async def test_create_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -617,7 +635,6 @@ async def test_create_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation.Conversation() ) - await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -631,7 +648,7 @@ async def test_create_conversation_field_headers_async(): def test_create_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -639,7 +656,6 @@ def test_create_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation( @@ -651,14 +667,12 @@ def test_create_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") def test_create_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -672,7 +686,9 @@ def test_create_conversation_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -695,15 +711,15 @@ async def test_create_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") @pytest.mark.asyncio async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -719,7 +735,7 @@ def test_list_conversations( transport: str = "grpc", request_type=conversation.ListConversationsRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -734,19 +750,15 @@ def test_list_conversations( call.return_value = conversation.ListConversationsResponse( next_page_token="next_page_token_value", ) - response = client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == "next_page_token_value" @@ -758,7 +770,7 @@ def test_list_conversations_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -768,7 +780,6 @@ def test_list_conversations_empty_call(): client.list_conversations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() @@ -777,7 +788,7 @@ async def test_list_conversations_async( transport: str = "grpc_asyncio", request_type=conversation.ListConversationsRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -794,18 +805,15 @@ async def test_list_conversations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -815,11 +823,12 @@ async def test_list_conversations_async_from_dict(): def test_list_conversations_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -827,7 +836,6 @@ def test_list_conversations_field_headers(): type(client.transport.list_conversations), "__call__" ) as call: call.return_value = conversation.ListConversationsResponse() - client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -842,11 +850,14 @@ def test_list_conversations_field_headers(): @pytest.mark.asyncio async def test_list_conversations_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -856,7 +867,6 @@ async def test_list_conversations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListConversationsResponse() ) - await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -870,7 +880,7 @@ async def test_list_conversations_field_headers_async(): def test_list_conversations_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -878,7 +888,6 @@ def test_list_conversations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversations(parent="parent_value",) @@ -887,12 +896,11 @@ def test_list_conversations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversations_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -904,7 +912,9 @@ def test_list_conversations_flattened_error(): @pytest.mark.asyncio async def test_list_conversations_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -924,13 +934,14 @@ async def test_list_conversations_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_conversations_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -941,7 +952,7 @@ async def test_list_conversations_flattened_error_async(): def test_list_conversations_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -986,7 +997,7 @@ def test_list_conversations_pager(): def test_list_conversations_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1023,7 +1034,7 @@ def test_list_conversations_pages(): @pytest.mark.asyncio async def test_list_conversations_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1067,7 +1078,7 @@ async def test_list_conversations_async_pager(): @pytest.mark.asyncio async def test_list_conversations_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1110,7 +1121,7 @@ def test_get_conversation( transport: str = "grpc", request_type=conversation.GetConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1126,27 +1137,20 @@ def test_get_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1161,7 +1165,7 @@ def test_get_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1169,7 +1173,6 @@ def test_get_conversation_empty_call(): client.get_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() @@ -1178,7 +1181,7 @@ async def test_get_conversation_async( transport: str = "grpc_asyncio", request_type=conversation.GetConversationRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1196,26 +1199,20 @@ async def test_get_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1228,17 +1225,17 @@ async def test_get_conversation_async_from_dict(): def test_get_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: call.return_value = conversation.Conversation() - client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1253,11 +1250,14 @@ def test_get_conversation_field_headers(): @pytest.mark.asyncio async def test_get_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1265,7 +1265,6 @@ async def test_get_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1279,13 +1278,12 @@ async def test_get_conversation_field_headers_async(): def test_get_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation(name="name_value",) @@ -1294,12 +1292,11 @@ def test_get_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1311,7 +1308,9 @@ def test_get_conversation_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: @@ -1329,13 +1328,14 @@ async def test_get_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1349,7 +1349,7 @@ def test_complete_conversation( transport: str = "grpc", request_type=conversation.CompleteConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1367,27 +1367,20 @@ def test_complete_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1402,7 +1395,7 @@ def test_complete_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1412,7 +1405,6 @@ def test_complete_conversation_empty_call(): client.complete_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() @@ -1422,7 +1414,7 @@ async def test_complete_conversation_async( request_type=conversation.CompleteConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1442,26 +1434,20 @@ async def test_complete_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1474,11 +1460,12 @@ async def test_complete_conversation_async_from_dict(): def test_complete_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1486,7 +1473,6 @@ def test_complete_conversation_field_headers(): type(client.transport.complete_conversation), "__call__" ) as call: call.return_value = conversation.Conversation() - client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1501,11 +1487,14 @@ def test_complete_conversation_field_headers(): @pytest.mark.asyncio async def test_complete_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1504,6 @@ async def test_complete_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1529,7 +1517,7 @@ async def test_complete_conversation_field_headers_async(): def test_complete_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1537,7 +1525,6 @@ def test_complete_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.complete_conversation(name="name_value",) @@ -1546,12 +1533,11 @@ def test_complete_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_complete_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1563,7 +1549,9 @@ def test_complete_conversation_flattened_error(): @pytest.mark.asyncio async def test_complete_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1583,13 +1571,14 @@ async def test_complete_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1603,7 +1592,7 @@ def test_list_messages( transport: str = "grpc", request_type=conversation.ListMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1616,19 +1605,15 @@ def test_list_messages( call.return_value = conversation.ListMessagesResponse( next_page_token="next_page_token_value", ) - response = client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == "next_page_token_value" @@ -1640,7 +1625,7 @@ def test_list_messages_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1648,7 +1633,6 @@ def test_list_messages_empty_call(): client.list_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() @@ -1657,7 +1641,7 @@ async def test_list_messages_async( transport: str = "grpc_asyncio", request_type=conversation.ListMessagesRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1670,18 +1654,15 @@ async def test_list_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMessagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1691,17 +1672,17 @@ async def test_list_messages_async_from_dict(): def test_list_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: call.return_value = conversation.ListMessagesResponse() - client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1716,11 +1697,14 @@ def test_list_messages_field_headers(): @pytest.mark.asyncio async def test_list_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1728,7 +1712,6 @@ async def test_list_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse() ) - await client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1742,13 +1725,12 @@ async def test_list_messages_field_headers_async(): def test_list_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_messages(parent="parent_value",) @@ -1757,12 +1739,11 @@ def test_list_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1774,7 +1755,9 @@ def test_list_messages_flattened_error(): @pytest.mark.asyncio async def test_list_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1792,13 +1775,14 @@ async def test_list_messages_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1809,7 +1793,7 @@ async def test_list_messages_flattened_error_async(): def test_list_messages_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1847,7 +1831,7 @@ def test_list_messages_pager(): def test_list_messages_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1877,7 +1861,7 @@ def test_list_messages_pages(): @pytest.mark.asyncio async def test_list_messages_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1914,7 +1898,7 @@ async def test_list_messages_async_pager(): @pytest.mark.asyncio async def test_list_messages_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1949,16 +1933,16 @@ async def test_list_messages_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -1968,7 +1952,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -1979,7 +1963,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationsClient(transport=transport) assert client.transport is transport @@ -1988,13 +1972,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2009,23 +1993,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ConversationsGrpcTransport,) def test_conversations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2037,7 +2021,7 @@ def test_conversations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2054,15 +2038,40 @@ def test_conversations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2078,19 +2087,36 @@ def test_conversations_base_transport_with_credentials_file(): def test_conversations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ConversationsClient() adc.assert_called_once_with( scopes=( @@ -2101,14 +2127,44 @@ def test_conversations_auth_adc(): ) -def test_conversations_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ConversationsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2118,6 +2174,121 @@ def test_conversations_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2126,7 +2297,7 @@ def test_conversations_transport_auth_adc(): ], ) def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2168,7 +2339,7 @@ def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_clas def test_conversations_host_no_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2178,7 +2349,7 @@ def test_conversations_host_no_port(): def test_conversations_host_with_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2232,9 +2403,9 @@ def test_conversations_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2317,7 +2488,6 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): def test_conversation_path(): project = "squid" conversation = "clam" - expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, ) @@ -2340,7 +2510,6 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): project = "oyster" conversation_profile = "nudibranch" - expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2366,7 +2535,6 @@ def test_message_path(): project = "winkle" conversation = "nautilus" message = "scallop" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2389,7 +2557,6 @@ def test_parse_message_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2410,7 +2577,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) assert expected == actual @@ -2429,7 +2595,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) assert expected == actual @@ -2448,7 +2613,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) assert expected == actual @@ -2468,7 +2632,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2495,7 +2658,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationsTransport, "_prep_wrapped_messages" ) as prep: client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2504,6 +2667,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_documents.py b/tests/unit/gapic/dialogflow_v2/test_documents.py index e61b3a1e7..67c808518 100644 --- a/tests/unit/gapic/dialogflow_v2/test_documents.py +++ b/tests/unit/gapic/dialogflow_v2/test_documents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.documents import DocumentsAsyncClient from google.cloud.dialogflow_v2.services.documents import DocumentsClient from google.cloud.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.services.documents import transports +from google.cloud.dialogflow_v2.services.documents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.documents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_documents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -154,7 +183,7 @@ def test_documents_client_get_transport_class(): def test_documents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(DocumentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -438,7 +467,7 @@ def test_list_documents( transport: str = "grpc", request_type=document.ListDocumentsRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -451,19 +480,15 @@ def test_list_documents( call.return_value = document.ListDocumentsResponse( next_page_token="next_page_token_value", ) - response = client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == "next_page_token_value" @@ -475,7 +500,7 @@ def test_list_documents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -483,7 +508,6 @@ def test_list_documents_empty_call(): client.list_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() @@ -492,7 +516,7 @@ async def test_list_documents_async( transport: str = "grpc_asyncio", request_type=document.ListDocumentsRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -505,18 +529,15 @@ async def test_list_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -526,17 +547,17 @@ async def test_list_documents_async_from_dict(): def test_list_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: call.return_value = document.ListDocumentsResponse() - client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -551,11 +572,12 @@ def test_list_documents_field_headers(): @pytest.mark.asyncio async def test_list_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -563,7 +585,6 @@ async def test_list_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse() ) - await client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -577,13 +598,12 @@ async def test_list_documents_field_headers_async(): def test_list_documents_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_documents(parent="parent_value",) @@ -592,12 +612,11 @@ def test_list_documents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_documents_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -609,7 +628,7 @@ def test_list_documents_flattened_error(): @pytest.mark.asyncio async def test_list_documents_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -627,13 +646,12 @@ async def test_list_documents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_documents_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -644,7 +662,7 @@ async def test_list_documents_flattened_error_async(): def test_list_documents_pager(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -682,7 +700,7 @@ def test_list_documents_pager(): def test_list_documents_pages(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -712,7 +730,7 @@ def test_list_documents_pages(): @pytest.mark.asyncio async def test_list_documents_async_pager(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -749,7 +767,7 @@ async def test_list_documents_async_pager(): @pytest.mark.asyncio async def test_list_documents_async_pages(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -785,7 +803,7 @@ def test_get_document( transport: str = "grpc", request_type=document.GetDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -803,27 +821,19 @@ def test_get_document( enable_auto_reload=True, content_uri="content_uri_value", ) - response = client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -835,7 +845,7 @@ def test_get_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -843,7 +853,6 @@ def test_get_document_empty_call(): client.get_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() @@ -852,7 +861,7 @@ async def test_get_document_async( transport: str = "grpc_asyncio", request_type=document.GetDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -871,26 +880,19 @@ async def test_get_document_async( enable_auto_reload=True, ) ) - response = await client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -900,17 +902,17 @@ async def test_get_document_async_from_dict(): def test_get_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = document.Document() - client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -925,17 +927,17 @@ def test_get_document_field_headers(): @pytest.mark.asyncio async def test_get_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -949,13 +951,12 @@ async def test_get_document_field_headers_async(): def test_get_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_document(name="name_value",) @@ -964,12 +965,11 @@ def test_get_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -981,7 +981,7 @@ def test_get_document_flattened_error(): @pytest.mark.asyncio async def test_get_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: @@ -997,13 +997,12 @@ async def test_get_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1017,7 +1016,7 @@ def test_create_document( transport: str = "grpc", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1028,13 +1027,11 @@ def test_create_document( with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1049,7 +1046,7 @@ def test_create_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1057,7 +1054,6 @@ def test_create_document_empty_call(): client.create_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() @@ -1066,7 +1062,7 @@ async def test_create_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1079,13 +1075,11 @@ async def test_create_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1098,17 +1092,17 @@ async def test_create_document_async_from_dict(): def test_create_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1123,11 +1117,12 @@ def test_create_document_field_headers(): @pytest.mark.asyncio async def test_create_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1135,7 +1130,6 @@ async def test_create_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1149,13 +1143,12 @@ async def test_create_document_field_headers_async(): def test_create_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_document( @@ -1166,14 +1159,12 @@ def test_create_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") def test_create_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1187,7 +1178,7 @@ def test_create_document_flattened_error(): @pytest.mark.asyncio async def test_create_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: @@ -1207,15 +1198,13 @@ async def test_create_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") @pytest.mark.asyncio async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1231,7 +1220,7 @@ def test_delete_document( transport: str = "grpc", request_type=document.DeleteDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,13 +1231,11 @@ def test_delete_document( with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1263,7 +1250,7 @@ def test_delete_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1271,7 +1258,6 @@ def test_delete_document_empty_call(): client.delete_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() @@ -1280,7 +1266,7 @@ async def test_delete_document_async( transport: str = "grpc_asyncio", request_type=document.DeleteDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1293,13 +1279,11 @@ async def test_delete_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1312,17 +1296,17 @@ async def test_delete_document_async_from_dict(): def test_delete_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1337,11 +1321,12 @@ def test_delete_document_field_headers(): @pytest.mark.asyncio async def test_delete_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1349,7 +1334,6 @@ async def test_delete_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1363,13 +1347,12 @@ async def test_delete_document_field_headers_async(): def test_delete_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_document(name="name_value",) @@ -1378,12 +1361,11 @@ def test_delete_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1395,7 +1377,7 @@ def test_delete_document_flattened_error(): @pytest.mark.asyncio async def test_delete_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: @@ -1413,13 +1395,12 @@ async def test_delete_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1414,7 @@ def test_update_document( transport: str = "grpc", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1444,13 +1425,11 @@ def test_update_document( with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1465,7 +1444,7 @@ def test_update_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1473,7 +1452,6 @@ def test_update_document_empty_call(): client.update_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() @@ -1482,7 +1460,7 @@ async def test_update_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1495,13 +1473,11 @@ async def test_update_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1514,17 +1490,17 @@ async def test_update_document_async_from_dict(): def test_update_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1541,11 +1517,12 @@ def test_update_document_field_headers(): @pytest.mark.asyncio async def test_update_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1553,7 +1530,6 @@ async def test_update_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1569,32 +1545,29 @@ async def test_update_document_field_headers_async(): def test_update_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_document( document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == gcd_document.Document(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1602,13 +1575,13 @@ def test_update_document_flattened_error(): client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: @@ -1622,22 +1595,20 @@ async def test_update_document_flattened_async(): # using the keyword arguments to the method. response = await client.update_document( document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == gcd_document.Document(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1645,7 +1616,7 @@ async def test_update_document_flattened_error_async(): await client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1653,7 +1624,7 @@ def test_reload_document( transport: str = "grpc", request_type=document.ReloadDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1664,13 +1635,11 @@ def test_reload_document( with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1685,7 +1654,7 @@ def test_reload_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1662,6 @@ def test_reload_document_empty_call(): client.reload_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() @@ -1702,7 +1670,7 @@ async def test_reload_document_async( transport: str = "grpc_asyncio", request_type=document.ReloadDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1715,13 +1683,11 @@ async def test_reload_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1734,17 +1700,17 @@ async def test_reload_document_async_from_dict(): def test_reload_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1759,11 +1725,12 @@ def test_reload_document_field_headers(): @pytest.mark.asyncio async def test_reload_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1771,7 +1738,6 @@ async def test_reload_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1785,13 +1751,12 @@ async def test_reload_document_field_headers_async(): def test_reload_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.reload_document( @@ -1802,14 +1767,12 @@ def test_reload_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].content_uri == "content_uri_value" def test_reload_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1823,7 +1786,7 @@ def test_reload_document_flattened_error(): @pytest.mark.asyncio async def test_reload_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: @@ -1843,15 +1806,13 @@ async def test_reload_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].content_uri == "content_uri_value" @pytest.mark.asyncio async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1866,16 +1827,16 @@ async def test_reload_document_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -1885,7 +1846,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -1896,7 +1857,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DocumentsClient(transport=transport) assert client.transport is transport @@ -1905,13 +1866,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1923,23 +1884,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DocumentsGrpcTransport,) def test_documents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1951,7 +1912,7 @@ def test_documents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1974,15 +1935,40 @@ def test_documents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_documents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1998,19 +1984,36 @@ def test_documents_base_transport_with_credentials_file(): def test_documents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_documents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) DocumentsClient() adc.assert_called_once_with( scopes=( @@ -2021,14 +2024,38 @@ def test_documents_auth_adc(): ) -def test_documents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_documents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.DocumentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_documents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2038,12 +2065,123 @@ def test_documents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport], ) def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2085,7 +2223,7 @@ def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_documents_host_no_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2095,7 +2233,7 @@ def test_documents_host_no_port(): def test_documents_host_with_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2146,9 +2284,9 @@ def test_documents_transport_channel_mtls_with_client_cert_source(transport_clas mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2227,7 +2365,7 @@ def test_documents_transport_channel_mtls_with_adc(transport_class): def test_documents_grpc_lro_client(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2240,7 +2378,7 @@ def test_documents_grpc_lro_client(): def test_documents_grpc_lro_async_client(): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2255,7 +2393,6 @@ def test_document_path(): project = "squid" knowledge_base = "clam" document = "whelk" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2278,7 +2415,6 @@ def test_parse_document_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2299,7 +2435,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = DocumentsClient.common_folder_path(folder) assert expected == actual @@ -2318,7 +2453,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = DocumentsClient.common_organization_path(organization) assert expected == actual @@ -2337,7 +2471,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = DocumentsClient.common_project_path(project) assert expected == actual @@ -2357,7 +2490,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2384,7 +2516,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DocumentsTransport, "_prep_wrapped_messages" ) as prep: client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2393,6 +2525,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DocumentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_entity_types.py b/tests/unit/gapic/dialogflow_v2/test_entity_types.py index a35603f06..721584b26 100644 --- a/tests/unit/gapic/dialogflow_v2/test_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2/test_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,27 +23,57 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.entity_types import EntityTypesAsyncClient from google.cloud.dialogflow_v2.services.entity_types import EntityTypesClient from google.cloud.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.services.entity_types import transports +from google.cloud.dialogflow_v2.services.entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_entity_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -440,7 +469,7 @@ def test_list_entity_types( transport: str = "grpc", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -455,19 +484,15 @@ def test_list_entity_types( call.return_value = entity_type.ListEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -479,7 +504,7 @@ def test_list_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -489,7 +514,6 @@ def test_list_entity_types_empty_call(): client.list_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() @@ -498,7 +522,7 @@ async def test_list_entity_types_async( transport: str = "grpc_asyncio", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -515,18 +539,15 @@ async def test_list_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -536,11 +557,12 @@ async def test_list_entity_types_async_from_dict(): def test_list_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -548,7 +570,6 @@ def test_list_entity_types_field_headers(): type(client.transport.list_entity_types), "__call__" ) as call: call.return_value = entity_type.ListEntityTypesResponse() - client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -563,11 +584,12 @@ def test_list_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -577,7 +599,6 @@ async def test_list_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.ListEntityTypesResponse() ) - await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -591,7 +612,7 @@ async def test_list_entity_types_field_headers_async(): def test_list_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -599,7 +620,6 @@ def test_list_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_entity_types( @@ -610,14 +630,12 @@ def test_list_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" def test_list_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -631,7 +649,7 @@ def test_list_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -653,15 +671,13 @@ async def test_list_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -674,7 +690,7 @@ async def test_list_entity_types_flattened_error_async(): def test_list_entity_types_pager(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -716,7 +732,7 @@ def test_list_entity_types_pager(): def test_list_entity_types_pages(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -750,7 +766,7 @@ def test_list_entity_types_pages(): @pytest.mark.asyncio async def test_list_entity_types_async_pager(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -791,7 +807,7 @@ async def test_list_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_entity_types_async_pages(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -831,7 +847,7 @@ def test_get_entity_type( transport: str = "grpc", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -848,30 +864,22 @@ def test_get_entity_type( auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -883,7 +891,7 @@ def test_get_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -891,7 +899,6 @@ def test_get_entity_type_empty_call(): client.get_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() @@ -900,7 +907,7 @@ async def test_get_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -919,29 +926,22 @@ async def test_get_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -951,17 +951,17 @@ async def test_get_entity_type_async_from_dict(): def test_get_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: call.return_value = entity_type.EntityType() - client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -976,11 +976,12 @@ def test_get_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -988,7 +989,6 @@ async def test_get_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.EntityType() ) - await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1002,13 +1002,12 @@ async def test_get_entity_type_field_headers_async(): def test_get_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_entity_type( @@ -1019,14 +1018,12 @@ def test_get_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" def test_get_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1040,7 +1037,7 @@ def test_get_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: @@ -1060,15 +1057,13 @@ async def test_get_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1084,7 +1079,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcd_entity_type.CreateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1103,30 +1098,22 @@ def test_create_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1138,7 +1125,7 @@ def test_create_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1148,7 +1135,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() @@ -1158,7 +1144,7 @@ async def test_create_entity_type_async( request_type=gcd_entity_type.CreateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1179,29 +1165,22 @@ async def test_create_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1211,11 +1190,12 @@ async def test_create_entity_type_async_from_dict(): def test_create_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1223,7 +1203,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1238,11 +1217,12 @@ def test_create_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1252,7 +1232,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1266,7 +1245,7 @@ async def test_create_entity_type_field_headers_async(): def test_create_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1274,7 +1253,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_entity_type( @@ -1287,16 +1265,13 @@ def test_create_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" def test_create_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1311,7 +1286,7 @@ def test_create_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1335,17 +1310,14 @@ async def test_create_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1362,7 +1334,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcd_entity_type.UpdateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1381,30 +1353,22 @@ def test_update_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1416,7 +1380,7 @@ def test_update_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1426,7 +1390,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() @@ -1436,7 +1399,7 @@ async def test_update_entity_type_async( request_type=gcd_entity_type.UpdateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1457,29 +1420,22 @@ async def test_update_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1489,11 +1445,12 @@ async def test_update_entity_type_async_from_dict(): def test_update_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1501,7 +1458,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1518,11 +1474,12 @@ def test_update_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,7 +1489,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1548,7 +1504,7 @@ async def test_update_entity_type_field_headers_async(): def test_update_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1556,7 +1512,6 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_entity_type( @@ -1568,14 +1523,12 @@ def test_update_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" def test_update_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1589,7 +1542,7 @@ def test_update_entity_type_flattened_error(): @pytest.mark.asyncio async def test_update_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1612,15 +1565,13 @@ async def test_update_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1636,7 +1587,7 @@ def test_delete_entity_type( transport: str = "grpc", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1649,13 +1600,11 @@ def test_delete_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1670,7 +1619,7 @@ def test_delete_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1680,7 +1629,6 @@ def test_delete_entity_type_empty_call(): client.delete_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() @@ -1689,7 +1637,7 @@ async def test_delete_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1702,13 +1650,11 @@ async def test_delete_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1721,11 +1667,12 @@ async def test_delete_entity_type_async_from_dict(): def test_delete_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1733,7 +1680,6 @@ def test_delete_entity_type_field_headers(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = None - client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1748,11 +1694,12 @@ def test_delete_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1760,7 +1707,6 @@ async def test_delete_entity_type_field_headers_async(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1774,7 +1720,7 @@ async def test_delete_entity_type_field_headers_async(): def test_delete_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1782,7 +1728,6 @@ def test_delete_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_entity_type(name="name_value",) @@ -1791,12 +1736,11 @@ def test_delete_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1808,7 +1752,7 @@ def test_delete_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1826,13 +1770,12 @@ async def test_delete_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1846,7 +1789,7 @@ def test_batch_update_entity_types( transport: str = "grpc", request_type=entity_type.BatchUpdateEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1859,13 +1802,11 @@ def test_batch_update_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1880,7 +1821,7 @@ def test_batch_update_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1890,7 +1831,6 @@ def test_batch_update_entity_types_empty_call(): client.batch_update_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() @@ -1900,7 +1840,7 @@ async def test_batch_update_entity_types_async( request_type=entity_type.BatchUpdateEntityTypesRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1915,13 +1855,11 @@ async def test_batch_update_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1934,11 +1872,12 @@ async def test_batch_update_entity_types_async_from_dict(): def test_batch_update_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1946,7 +1885,6 @@ def test_batch_update_entity_types_field_headers(): type(client.transport.batch_update_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1961,11 +1899,12 @@ def test_batch_update_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_update_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1975,7 +1914,6 @@ async def test_batch_update_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1992,7 +1930,7 @@ def test_batch_delete_entity_types( transport: str = "grpc", request_type=entity_type.BatchDeleteEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2005,13 +1943,11 @@ def test_batch_delete_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2026,7 +1962,7 @@ def test_batch_delete_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2036,7 +1972,6 @@ def test_batch_delete_entity_types_empty_call(): client.batch_delete_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() @@ -2046,7 +1981,7 @@ async def test_batch_delete_entity_types_async( request_type=entity_type.BatchDeleteEntityTypesRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2061,13 +1996,11 @@ async def test_batch_delete_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2080,11 +2013,12 @@ async def test_batch_delete_entity_types_async_from_dict(): def test_batch_delete_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2092,7 +2026,6 @@ def test_batch_delete_entity_types_field_headers(): type(client.transport.batch_delete_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2107,11 +2040,12 @@ def test_batch_delete_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2121,7 +2055,6 @@ async def test_batch_delete_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2135,7 +2068,7 @@ async def test_batch_delete_entity_types_field_headers_async(): def test_batch_delete_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2143,7 +2076,6 @@ def test_batch_delete_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_entity_types( @@ -2154,14 +2086,12 @@ def test_batch_delete_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type_names == ["entity_type_names_value"] def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2175,7 +2105,7 @@ def test_batch_delete_entity_types_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2197,15 +2127,13 @@ async def test_batch_delete_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type_names == ["entity_type_names_value"] @pytest.mark.asyncio async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2221,7 +2149,7 @@ def test_batch_create_entities( transport: str = "grpc", request_type=entity_type.BatchCreateEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2234,13 +2162,11 @@ def test_batch_create_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2255,7 +2181,7 @@ def test_batch_create_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2265,7 +2191,6 @@ def test_batch_create_entities_empty_call(): client.batch_create_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() @@ -2274,7 +2199,7 @@ async def test_batch_create_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchCreateEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2289,13 +2214,11 @@ async def test_batch_create_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2308,11 +2231,12 @@ async def test_batch_create_entities_async_from_dict(): def test_batch_create_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2320,7 +2244,6 @@ def test_batch_create_entities_field_headers(): type(client.transport.batch_create_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2335,11 +2258,12 @@ def test_batch_create_entities_field_headers(): @pytest.mark.asyncio async def test_batch_create_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2349,7 +2273,6 @@ async def test_batch_create_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2363,7 +2286,7 @@ async def test_batch_create_entities_field_headers_async(): def test_batch_create_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2371,7 +2294,6 @@ def test_batch_create_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_create_entities( @@ -2384,16 +2306,13 @@ def test_batch_create_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_create_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2408,7 +2327,7 @@ def test_batch_create_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_create_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2432,17 +2351,14 @@ async def test_batch_create_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2459,7 +2375,7 @@ def test_batch_update_entities( transport: str = "grpc", request_type=entity_type.BatchUpdateEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2472,13 +2388,11 @@ def test_batch_update_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2493,7 +2407,7 @@ def test_batch_update_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2503,7 +2417,6 @@ def test_batch_update_entities_empty_call(): client.batch_update_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() @@ -2512,7 +2425,7 @@ async def test_batch_update_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchUpdateEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2527,13 +2440,11 @@ async def test_batch_update_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2546,11 +2457,12 @@ async def test_batch_update_entities_async_from_dict(): def test_batch_update_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2558,7 +2470,6 @@ def test_batch_update_entities_field_headers(): type(client.transport.batch_update_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2573,11 +2484,12 @@ def test_batch_update_entities_field_headers(): @pytest.mark.asyncio async def test_batch_update_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2587,7 +2499,6 @@ async def test_batch_update_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2601,7 +2512,7 @@ async def test_batch_update_entities_field_headers_async(): def test_batch_update_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2609,7 +2520,6 @@ def test_batch_update_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_update_entities( @@ -2622,16 +2532,13 @@ def test_batch_update_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_update_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2646,7 +2553,7 @@ def test_batch_update_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_update_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2670,17 +2577,14 @@ async def test_batch_update_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2697,7 +2601,7 @@ def test_batch_delete_entities( transport: str = "grpc", request_type=entity_type.BatchDeleteEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2710,13 +2614,11 @@ def test_batch_delete_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2731,7 +2633,7 @@ def test_batch_delete_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2741,7 +2643,6 @@ def test_batch_delete_entities_empty_call(): client.batch_delete_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() @@ -2750,7 +2651,7 @@ async def test_batch_delete_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchDeleteEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2765,13 +2666,11 @@ async def test_batch_delete_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2784,11 +2683,12 @@ async def test_batch_delete_entities_async_from_dict(): def test_batch_delete_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2796,7 +2696,6 @@ def test_batch_delete_entities_field_headers(): type(client.transport.batch_delete_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2811,11 +2710,12 @@ def test_batch_delete_entities_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2825,7 +2725,6 @@ async def test_batch_delete_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2839,7 +2738,7 @@ async def test_batch_delete_entities_field_headers_async(): def test_batch_delete_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2847,7 +2746,6 @@ def test_batch_delete_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_entities( @@ -2860,16 +2758,13 @@ def test_batch_delete_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2884,7 +2779,7 @@ def test_batch_delete_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2908,17 +2803,14 @@ async def test_batch_delete_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2934,16 +2826,16 @@ async def test_batch_delete_entities_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -2953,7 +2845,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -2964,7 +2856,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EntityTypesClient(transport=transport) assert client.transport is transport @@ -2973,13 +2865,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2991,23 +2883,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EntityTypesGrpcTransport,) def test_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3019,7 +2911,7 @@ def test_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3046,15 +2938,40 @@ def test_entity_types_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3070,19 +2987,36 @@ def test_entity_types_base_transport_with_credentials_file(): def test_entity_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) EntityTypesClient() adc.assert_called_once_with( scopes=( @@ -3093,14 +3027,38 @@ def test_entity_types_auth_adc(): ) -def test_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -3110,12 +3068,127 @@ def test_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport], ) def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3157,7 +3230,7 @@ def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class def test_entity_types_host_no_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3167,7 +3240,7 @@ def test_entity_types_host_no_port(): def test_entity_types_host_with_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3218,9 +3291,9 @@ def test_entity_types_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3299,7 +3372,7 @@ def test_entity_types_transport_channel_mtls_with_adc(transport_class): def test_entity_types_grpc_lro_client(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3312,7 +3385,7 @@ def test_entity_types_grpc_lro_client(): def test_entity_types_grpc_lro_async_client(): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3326,7 +3399,6 @@ def test_entity_types_grpc_lro_async_client(): def test_entity_type_path(): project = "squid" entity_type = "clam" - expected = "projects/{project}/agent/entityTypes/{entity_type}".format( project=project, entity_type=entity_type, ) @@ -3348,7 +3420,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3369,7 +3440,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -3388,7 +3458,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -3407,7 +3476,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -3427,7 +3495,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3454,7 +3521,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3463,6 +3530,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_environments.py b/tests/unit/gapic/dialogflow_v2/test_environments.py index df149b933..685e71673 100644 --- a/tests/unit/gapic/dialogflow_v2/test_environments.py +++ b/tests/unit/gapic/dialogflow_v2/test_environments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,20 +23,54 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.environments import EnvironmentsAsyncClient from google.cloud.dialogflow_v2.services.environments import EnvironmentsClient from google.cloud.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.services.environments import transports +from google.cloud.dialogflow_v2.services.environments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.environments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -83,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +131,7 @@ def test_environments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -149,7 +182,7 @@ def test_environments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EnvironmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -433,7 +466,7 @@ def test_list_environments( transport: str = "grpc", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -448,19 +481,15 @@ def test_list_environments( call.return_value = environment.ListEnvironmentsResponse( next_page_token="next_page_token_value", ) - response = client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == "next_page_token_value" @@ -472,7 +501,7 @@ def test_list_environments_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -482,7 +511,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -491,7 +519,7 @@ async def test_list_environments_async( transport: str = "grpc_asyncio", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -508,18 +536,15 @@ async def test_list_environments_async( next_page_token="next_page_token_value", ) ) - response = await client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -529,11 +554,12 @@ async def test_list_environments_async_from_dict(): def test_list_environments_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -541,7 +567,6 @@ def test_list_environments_field_headers(): type(client.transport.list_environments), "__call__" ) as call: call.return_value = environment.ListEnvironmentsResponse() - client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -556,11 +581,12 @@ def test_list_environments_field_headers(): @pytest.mark.asyncio async def test_list_environments_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -570,7 +596,6 @@ async def test_list_environments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.ListEnvironmentsResponse() ) - await client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -583,8 +608,76 @@ async def test_list_environments_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] +def test_list_environments_flattened(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_environments(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_environments( + environment.ListEnvironmentsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.ListEnvironmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_environments( + environment.ListEnvironmentsRequest(), parent="parent_value", + ) + + def test_list_environments_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -626,7 +719,7 @@ def test_list_environments_pager(): def test_list_environments_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -660,7 +753,7 @@ def test_list_environments_pages(): @pytest.mark.asyncio async def test_list_environments_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -701,7 +794,7 @@ async def test_list_environments_async_pager(): @pytest.mark.asyncio async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -737,180 +830,1291 @@ async def test_list_environments_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), +def test_get_environment( + transport: str = "grpc", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + response = client.get_environment(request) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_get_environment_async( + transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, transport=transport, + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) ) + response = await client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + request.name = "name/value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + call.return_value = environment.Environment() + client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - ) +@pytest.mark.asyncio +async def test_get_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("list_environments",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + request.name = "name/value" -def test_environments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file" - ) as load_creds, mock.patch( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() ) + await client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_environments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_environments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id=None, - ) +def test_create_environment( + transport: str = "grpc", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_environments_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" - ) - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + response = client.create_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() -@pytest.mark.parametrize( - "transport_class", - [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], -) -def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED - # Check ssl_channel_credentials is used if provided. + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async( + transport: str = "grpc_asyncio", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_update_environment( + transport: str = "grpc", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async( + transport: str = "grpc_asyncio", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +def test_delete_environment( + transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async( + transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_environment_history( + transport: str = "grpc", request_type=environment.GetEnvironmentHistoryRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async( + transport: str = "grpc_asyncio", + request_type=environment.GetEnvironmentHistoryRequest, +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + ) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory() + ) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_get_environment_history_pager(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) for i in results) + + +def test_get_environment_history_pages(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, environment.EnvironmentHistory.Entry) for i in responses + ) + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) + + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_environments", + "get_environment", + "create_environment", + "update_environment", + "delete_environment", + "get_environment_history", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_environments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_environments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_environments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_environments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], +) +def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: mock_ssl_channel_creds = mock.Mock() transport_class( @@ -950,7 +2154,7 @@ def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class def test_environments_host_no_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -960,7 +2164,7 @@ def test_environments_host_no_port(): def test_environments_host_with_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1011,9 +2215,9 @@ def test_environments_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1093,7 +2297,6 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environment_path(): project = "squid" environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format( project=project, environment=environment, ) @@ -1113,9 +2316,26 @@ def test_parse_environment_path(): assert expected == actual -def test_common_billing_account_path(): - billing_account = "oyster" +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1125,7 +2345,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -1135,8 +2355,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -1144,7 +2363,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = EnvironmentsClient.common_folder_path(**expected) @@ -1154,8 +2373,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -1163,7 +2381,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = EnvironmentsClient.common_organization_path(**expected) @@ -1173,8 +2391,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -1182,7 +2399,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = EnvironmentsClient.common_project_path(**expected) @@ -1192,9 +2409,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1204,8 +2420,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = EnvironmentsClient.common_location_path(**expected) @@ -1221,7 +2437,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EnvironmentsTransport, "_prep_wrapped_messages" ) as prep: client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1230,6 +2446,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EnvironmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py b/tests/unit/gapic/dialogflow_v2/test_fulfillments.py similarity index 70% rename from owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py rename to tests/unit/gapic/dialogflow_v2/test_fulfillments.py index 7dc3e46b3..339d0a583 100644 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py +++ b/tests/unit/gapic/dialogflow_v2/test_fulfillments.py @@ -34,8 +34,12 @@ from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsAsyncClient from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsClient from google.cloud.dialogflow_v2.services.fulfillments import transports -from google.cloud.dialogflow_v2.services.fulfillments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.fulfillments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import fulfillment from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment from google.oauth2 import service_account @@ -65,6 +69,7 @@ reason="This test requires google-api-core >= 1.26.0", ) + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -73,7 +78,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -84,36 +93,45 @@ def test__get_default_mtls_endpoint(): 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(api_endpoint) == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, - FulfillmentsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) def test_fulfillments_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, - FulfillmentsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) def test_fulfillments_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds @@ -123,7 +141,7 @@ def test_fulfillments_client_from_service_account_file(client_class): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_fulfillments_client_get_transport_class(): @@ -137,29 +155,42 @@ def test_fulfillments_client_get_transport_class(): assert transport == transports.FulfillmentsGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) -def test_fulfillments_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +def test_fulfillments_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + 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: + 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -175,7 +206,7 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -191,7 +222,7 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -211,13 +242,15 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans client = client_class() # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class() # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -230,24 +263,50 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +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: + 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) @@ -270,10 +329,18 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp # 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): + 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 @@ -294,9 +361,14 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -310,16 +382,23 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_fulfillments_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -332,16 +411,24 @@ def test_fulfillments_client_client_options_scopes(client_class, transport_class client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -356,11 +443,11 @@ def test_fulfillments_client_client_options_credentials_file(client_class, trans def test_fulfillments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + 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'} - ) + client = FulfillmentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -372,10 +459,11 @@ def test_fulfillments_client_client_options_from_dict(): ) -def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): +def test_get_fulfillment( + transport: str = "grpc", request_type=fulfillment.GetFulfillmentRequest +): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -383,15 +471,15 @@ def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFu 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: + 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', + name="name_value", + display_name="display_name_value", enabled=True, - generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + generic_web_service=fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), ) response = client.get_fulfillment(request) @@ -402,8 +490,8 @@ def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFu # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -415,14 +503,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: client.get_fulfillment() call.assert_called() _, args, _ = call.mock_calls[0] @@ -430,10 +515,11 @@ def test_get_fulfillment_empty_call(): @pytest.mark.asyncio -async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): +async def test_get_fulfillment_async( + transport: str = "grpc_asyncio", request_type=fulfillment.GetFulfillmentRequest +): client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -441,15 +527,13 @@ async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_ty 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: + 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, - )) + 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. @@ -459,8 +543,8 @@ async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_ty # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -470,20 +554,16 @@ async def test_get_fulfillment_async_from_dict(): def test_get_fulfillment_field_headers(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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' + 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: + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: call.return_value = fulfillment.Fulfillment() client.get_fulfillment(request) @@ -494,29 +574,24 @@ def test_get_fulfillment_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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()) + 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. @@ -526,96 +601,78 @@ async def test_get_fulfillment_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_fulfillment_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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', - ) + client.get_fulfillment(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_get_fulfillment_flattened_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + fulfillment.GetFulfillmentRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_fulfillment_flattened_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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.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', - ) + response = await client.get_fulfillment(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_fulfillment_flattened_error_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + fulfillment.GetFulfillmentRequest(), name="name_value", ) -def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): +def test_update_fulfillment( + transport: str = "grpc", request_type=gcd_fulfillment.UpdateFulfillmentRequest +): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -624,14 +681,16 @@ def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillmen # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + 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', + name="name_value", + display_name="display_name_value", enabled=True, - generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), ) response = client.update_fulfillment(request) @@ -642,8 +701,8 @@ def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillmen # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -655,14 +714,13 @@ 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', + 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: + type(client.transport.update_fulfillment), "__call__" + ) as call: client.update_fulfillment() call.assert_called() _, args, _ = call.mock_calls[0] @@ -670,10 +728,12 @@ def test_update_fulfillment_empty_call(): @pytest.mark.asyncio -async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): +async def test_update_fulfillment_async( + transport: str = "grpc_asyncio", + request_type=gcd_fulfillment.UpdateFulfillmentRequest, +): client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -682,14 +742,14 @@ async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + 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, - )) + 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. @@ -699,8 +759,8 @@ async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -710,20 +770,18 @@ async def test_update_fulfillment_async_from_dict(): def test_update_fulfillment_field_headers(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_fulfillment.UpdateFulfillmentRequest() - request.fulfillment.name = 'fulfillment.name/value' + request.fulfillment.name = "fulfillment.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + type(client.transport.update_fulfillment), "__call__" + ) as call: call.return_value = gcd_fulfillment.Fulfillment() client.update_fulfillment(request) @@ -734,29 +792,28 @@ def test_update_fulfillment_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'fulfillment.name=fulfillment.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] @pytest.mark.asyncio async def test_update_fulfillment_field_headers_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_fulfillment.UpdateFulfillmentRequest() - request.fulfillment.name = 'fulfillment.name/value' + request.fulfillment.name = "fulfillment.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + 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. @@ -766,95 +823,88 @@ async def test_update_fulfillment_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'fulfillment.name=fulfillment.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] def test_update_fulfillment_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_fulfillment_flattened_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + 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(), - ) + 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: + 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.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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_fulfillment_flattened_error_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -865,8 +915,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -885,8 +934,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = FulfillmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client_options={"scopes": ["1", "2"]}, transport=transport, ) @@ -898,6 +946,7 @@ def test_transport_instance(): 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( @@ -912,39 +961,42 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FulfillmentsGrpcTransport, - ) + 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" + 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: + 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(), @@ -953,8 +1005,8 @@ def test_fulfillments_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_fulfillment', - 'update_fulfillment', + "get_fulfillment", + "update_fulfillment", ) for method in methods: with pytest.raises(NotImplementedError): @@ -964,19 +1016,23 @@ def test_fulfillments_base_transport(): @requires_google_auth_gte_1_25_0 def test_fulfillments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -984,16 +1040,21 @@ def test_fulfillments_base_transport_with_credentials_file(): @requires_google_auth_lt_1_25_0 def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), quota_project_id="octopus", ) @@ -1001,7 +1062,9 @@ def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): 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: + 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() @@ -1011,15 +1074,15 @@ def test_fulfillments_base_transport_with_adc(): @requires_google_auth_gte_1_25_0 def test_fulfillments_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1027,11 +1090,14 @@ def test_fulfillments_auth_adc(): @requires_google_auth_lt_1_25_0 def test_fulfillments_auth_adc_old_google_auth(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) FulfillmentsClient() adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1047,12 +1113,15 @@ def test_fulfillments_auth_adc_old_google_auth(): 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: + 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',), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1071,10 +1140,11 @@ def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1083,22 +1153,21 @@ def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_gte_1_26_0 def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "dialogflow.googleapis.com:443", @@ -1106,9 +1175,9 @@ def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), scopes=["1", "2"], default_host="dialogflow.googleapis.com", ssl_credentials=None, @@ -1123,14 +1192,18 @@ def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 -def test_fulfillments_transport_create_channel_old_api_core(transport_class, grpc_helpers): +def test_fulfillments_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -1143,9 +1216,9 @@ def test_fulfillments_transport_create_channel_old_api_core(transport_class, grp credentials_file=None, quota_project_id="octopus", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), @@ -1158,14 +1231,18 @@ def test_fulfillments_transport_create_channel_old_api_core(transport_class, grp "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 -def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc_helpers): +def test_fulfillments_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -1187,10 +1264,11 @@ def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc ) -@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) -def test_fulfillments_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@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. @@ -1199,15 +1277,15 @@ def test_fulfillments_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, @@ -1223,37 +1301,40 @@ def test_fulfillments_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) def test_fulfillments_host_no_port(): client = FulfillmentsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_fulfillments_host_with_port(): client = FulfillmentsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' + assert client.transport._host == "dialogflow.googleapis.com:8000" + def test_fulfillments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1261,12 +1342,11 @@ def test_fulfillments_grpc_transport_channel(): def test_fulfillments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1275,12 +1355,17 @@ def test_fulfillments_grpc_asyncio_transport_channel(): # 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: +@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 @@ -1289,7 +1374,7 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1306,8 +1391,8 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -1322,17 +1407,20 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( # 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 -): +@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: + 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() @@ -1350,8 +1438,8 @@ def test_fulfillments_transport_channel_mtls_with_adc( credentials=mock_cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -1365,7 +1453,7 @@ def test_fulfillments_transport_channel_mtls_with_adc( def test_fulfillment_path(): project = "squid" - expected = "projects/{project}/agent/fulfillment".format(project=project, ) + expected = "projects/{project}/agent/fulfillment".format(project=project,) actual = FulfillmentsClient.fulfillment_path(project) assert expected == actual @@ -1380,9 +1468,12 @@ def test_parse_fulfillment_path(): 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, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = FulfillmentsClient.common_billing_account_path(billing_account) assert expected == actual @@ -1397,9 +1488,10 @@ def test_parse_common_billing_account_path(): actual = FulfillmentsClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format(folder=folder,) actual = FulfillmentsClient.common_folder_path(folder) assert expected == actual @@ -1414,9 +1506,10 @@ def test_parse_common_folder_path(): actual = FulfillmentsClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format(organization=organization,) actual = FulfillmentsClient.common_organization_path(organization) assert expected == actual @@ -1431,9 +1524,10 @@ def test_parse_common_organization_path(): actual = FulfillmentsClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format(project=project,) actual = FulfillmentsClient.common_project_path(project) assert expected == actual @@ -1448,10 +1542,13 @@ def test_parse_common_project_path(): 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, ) + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) actual = FulfillmentsClient.common_location_path(project, location) assert expected == actual @@ -1471,17 +1568,19 @@ def test_parse_common_location_path(): def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + 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, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_intents.py b/tests/unit/gapic/dialogflow_v2/test_intents.py index 0cbed51cb..e2d7623e6 100644 --- a/tests/unit/gapic/dialogflow_v2/test_intents.py +++ b/tests/unit/gapic/dialogflow_v2/test_intents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.intents import IntentsAsyncClient from google.cloud.dialogflow_v2.services.intents import IntentsClient from google.cloud.dialogflow_v2.services.intents import pagers from google.cloud.dialogflow_v2.services.intents import transports +from google.cloud.dialogflow_v2.services.intents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.intents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_intents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_intents_client_get_transport_class(): def test_intents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(IntentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_intents_client_client_options_from_dict(): def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -431,19 +460,15 @@ def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRe call.return_value = intent.ListIntentsResponse( next_page_token="next_page_token_value", ) - response = client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == "next_page_token_value" @@ -455,7 +480,7 @@ def test_list_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -463,7 +488,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -472,7 +496,7 @@ async def test_list_intents_async( transport: str = "grpc_asyncio", request_type=intent.ListIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,18 +509,15 @@ async def test_list_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListIntentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -506,17 +527,17 @@ async def test_list_intents_async_from_dict(): def test_list_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: call.return_value = intent.ListIntentsResponse() - client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -531,11 +552,12 @@ def test_list_intents_field_headers(): @pytest.mark.asyncio async def test_list_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ async def test_list_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse() ) - await client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -557,13 +578,12 @@ async def test_list_intents_field_headers_async(): def test_list_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_intents( @@ -574,14 +594,12 @@ def test_list_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" def test_list_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -595,7 +613,7 @@ def test_list_intents_flattened_error(): @pytest.mark.asyncio async def test_list_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -615,15 +633,13 @@ async def test_list_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -636,7 +652,7 @@ async def test_list_intents_flattened_error_async(): def test_list_intents_pager(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -668,7 +684,7 @@ def test_list_intents_pager(): def test_list_intents_pages(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -692,7 +708,7 @@ def test_list_intents_pages(): @pytest.mark.asyncio async def test_list_intents_async_pager(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -723,7 +739,7 @@ async def test_list_intents_async_pager(): @pytest.mark.asyncio async def test_list_intents_async_pages(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -751,7 +767,7 @@ async def test_list_intents_async_pages(): def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -778,49 +794,31 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -832,7 +830,7 @@ def test_get_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -840,7 +838,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -849,7 +846,7 @@ async def test_get_intent_async( transport: str = "grpc_asyncio", request_type=intent.GetIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -878,48 +875,31 @@ async def test_get_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -929,17 +909,17 @@ async def test_get_intent_async_from_dict(): def test_get_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = intent.Intent() - client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -954,17 +934,17 @@ def test_get_intent_field_headers(): @pytest.mark.asyncio async def test_get_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - await client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -978,13 +958,12 @@ async def test_get_intent_field_headers_async(): def test_get_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_intent( @@ -995,14 +974,12 @@ def test_get_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" def test_get_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1016,7 +993,7 @@ def test_get_intent_flattened_error(): @pytest.mark.asyncio async def test_get_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: @@ -1034,15 +1011,13 @@ async def test_get_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1058,7 +1033,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcd_intent.CreateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1085,51 +1060,33 @@ def test_create_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1141,7 +1098,7 @@ def test_create_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1149,7 +1106,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() @@ -1158,7 +1114,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcd_intent.CreateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1189,50 +1145,33 @@ async def test_create_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1242,17 +1181,17 @@ async def test_create_intent_async_from_dict(): def test_create_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = gcd_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1267,17 +1206,17 @@ def test_create_intent_field_headers(): @pytest.mark.asyncio async def test_create_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1291,13 +1230,12 @@ async def test_create_intent_field_headers_async(): def test_create_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1310,16 +1248,13 @@ def test_create_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" def test_create_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1334,7 +1269,7 @@ def test_create_intent_flattened_error(): @pytest.mark.asyncio async def test_create_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: @@ -1354,17 +1289,14 @@ async def test_create_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1381,7 +1313,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcd_intent.UpdateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1408,51 +1340,33 @@ def test_update_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1464,7 +1378,7 @@ def test_update_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1472,7 +1386,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() @@ -1481,7 +1394,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcd_intent.UpdateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1512,50 +1425,33 @@ async def test_update_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1565,17 +1461,17 @@ async def test_update_intent_async_from_dict(): def test_update_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = gcd_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1590,17 +1486,17 @@ def test_update_intent_field_headers(): @pytest.mark.asyncio async def test_update_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1614,35 +1510,31 @@ async def test_update_intent_field_headers_async(): def test_update_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcd_intent.Intent(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1651,13 +1543,13 @@ def test_update_intent_flattened_error(): gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: @@ -1670,24 +1562,21 @@ async def test_update_intent_flattened_async(): response = await client.update_intent( intent=gcd_intent.Intent(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1696,7 +1585,7 @@ async def test_update_intent_flattened_error_async(): gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1704,7 +1593,7 @@ def test_delete_intent( transport: str = "grpc", request_type=intent.DeleteIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1715,13 +1604,11 @@ def test_delete_intent( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1736,7 +1623,7 @@ def test_delete_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1744,7 +1631,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1753,7 +1639,7 @@ async def test_delete_intent_async( transport: str = "grpc_asyncio", request_type=intent.DeleteIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1764,13 +1650,11 @@ async def test_delete_intent_async( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1783,17 +1667,17 @@ async def test_delete_intent_async_from_dict(): def test_delete_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = None - client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1808,17 +1692,17 @@ def test_delete_intent_field_headers(): @pytest.mark.asyncio async def test_delete_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1832,13 +1716,12 @@ async def test_delete_intent_field_headers_async(): def test_delete_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_intent(name="name_value",) @@ -1847,12 +1730,11 @@ def test_delete_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1864,7 +1746,7 @@ def test_delete_intent_flattened_error(): @pytest.mark.asyncio async def test_delete_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: @@ -1880,13 +1762,12 @@ async def test_delete_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1900,7 +1781,7 @@ def test_batch_update_intents( transport: str = "grpc", request_type=intent.BatchUpdateIntentsRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1913,13 +1794,11 @@ def test_batch_update_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1934,7 +1813,7 @@ def test_batch_update_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1944,7 +1823,6 @@ def test_batch_update_intents_empty_call(): client.batch_update_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() @@ -1953,7 +1831,7 @@ async def test_batch_update_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchUpdateIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1968,13 +1846,11 @@ async def test_batch_update_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1987,11 +1863,12 @@ async def test_batch_update_intents_async_from_dict(): def test_batch_update_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1999,7 +1876,6 @@ def test_batch_update_intents_field_headers(): type(client.transport.batch_update_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2014,11 +1890,12 @@ def test_batch_update_intents_field_headers(): @pytest.mark.asyncio async def test_batch_update_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2028,7 +1905,6 @@ async def test_batch_update_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2042,7 +1918,7 @@ async def test_batch_update_intents_field_headers_async(): def test_batch_update_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2050,7 +1926,6 @@ def test_batch_update_intents_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_update_intents( @@ -2065,16 +1940,14 @@ def test_batch_update_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) def test_batch_update_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2091,7 +1964,7 @@ def test_batch_update_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_update_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2117,9 +1990,7 @@ async def test_batch_update_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) @@ -2127,7 +1998,7 @@ async def test_batch_update_intents_flattened_async(): @pytest.mark.asyncio async def test_batch_update_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2146,7 +2017,7 @@ def test_batch_delete_intents( transport: str = "grpc", request_type=intent.BatchDeleteIntentsRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2159,13 +2030,11 @@ def test_batch_delete_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2180,7 +2049,7 @@ def test_batch_delete_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2190,7 +2059,6 @@ def test_batch_delete_intents_empty_call(): client.batch_delete_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() @@ -2199,7 +2067,7 @@ async def test_batch_delete_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchDeleteIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2214,13 +2082,11 @@ async def test_batch_delete_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2233,11 +2099,12 @@ async def test_batch_delete_intents_async_from_dict(): def test_batch_delete_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2245,7 +2112,6 @@ def test_batch_delete_intents_field_headers(): type(client.transport.batch_delete_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2260,11 +2126,12 @@ def test_batch_delete_intents_field_headers(): @pytest.mark.asyncio async def test_batch_delete_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2274,7 +2141,6 @@ async def test_batch_delete_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2288,7 +2154,7 @@ async def test_batch_delete_intents_field_headers_async(): def test_batch_delete_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2296,7 +2162,6 @@ def test_batch_delete_intents_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_intents( @@ -2307,14 +2172,12 @@ def test_batch_delete_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] def test_batch_delete_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2328,7 +2191,7 @@ def test_batch_delete_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2350,15 +2213,13 @@ async def test_batch_delete_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] @pytest.mark.asyncio async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2373,16 +2234,16 @@ async def test_batch_delete_intents_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -2392,7 +2253,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -2403,7 +2264,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = IntentsClient(transport=transport) assert client.transport is transport @@ -2412,13 +2273,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.IntentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2430,23 +2291,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.IntentsGrpcTransport,) def test_intents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2458,7 +2319,7 @@ def test_intents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2482,15 +2343,40 @@ def test_intents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_intents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2506,19 +2392,36 @@ def test_intents_base_transport_with_credentials_file(): def test_intents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_intents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) IntentsClient() adc.assert_called_once_with( scopes=( @@ -2529,14 +2432,38 @@ def test_intents_auth_adc(): ) -def test_intents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_intents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.IntentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_intents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2546,12 +2473,123 @@ def test_intents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport], ) def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2593,7 +2631,7 @@ def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_intents_host_no_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2603,7 +2641,7 @@ def test_intents_host_no_port(): def test_intents_host_with_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2654,9 +2692,9 @@ def test_intents_transport_channel_mtls_with_client_cert_source(transport_class) mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2735,7 +2773,7 @@ def test_intents_transport_channel_mtls_with_adc(transport_class): def test_intents_grpc_lro_client(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2748,7 +2786,7 @@ def test_intents_grpc_lro_client(): def test_intents_grpc_lro_async_client(): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2763,7 +2801,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2787,7 +2824,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2809,7 +2845,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2830,7 +2865,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2849,7 +2883,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2868,7 +2901,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2888,7 +2920,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2915,7 +2946,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.IntentsTransport, "_prep_wrapped_messages" ) as prep: client = IntentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2924,6 +2955,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = IntentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py b/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py index d20501047..30cadb931 100644 --- a/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py +++ b/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.knowledge_bases import ( KnowledgeBasesAsyncClient, @@ -38,10 +37,40 @@ from google.cloud.dialogflow_v2.services.knowledge_bases import KnowledgeBasesClient from google.cloud.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.services.knowledge_bases import transports +from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -109,7 +138,7 @@ def test_knowledge_bases_client_from_service_account_info(client_class): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -162,7 +191,7 @@ def test_knowledge_bases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(KnowledgeBasesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -450,7 +479,7 @@ def test_list_knowledge_bases( transport: str = "grpc", request_type=knowledge_base.ListKnowledgeBasesRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,19 +494,15 @@ def test_list_knowledge_bases( call.return_value = knowledge_base.ListKnowledgeBasesResponse( next_page_token="next_page_token_value", ) - response = client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == "next_page_token_value" @@ -489,7 +514,7 @@ def test_list_knowledge_bases_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -499,7 +524,6 @@ def test_list_knowledge_bases_empty_call(): client.list_knowledge_bases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() @@ -509,7 +533,7 @@ async def test_list_knowledge_bases_async( request_type=knowledge_base.ListKnowledgeBasesRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,18 +550,15 @@ async def test_list_knowledge_bases_async( next_page_token="next_page_token_value", ) ) - response = await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -547,11 +568,12 @@ async def test_list_knowledge_bases_async_from_dict(): def test_list_knowledge_bases_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -559,7 +581,6 @@ def test_list_knowledge_bases_field_headers(): type(client.transport.list_knowledge_bases), "__call__" ) as call: call.return_value = knowledge_base.ListKnowledgeBasesResponse() - client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -574,11 +595,14 @@ def test_list_knowledge_bases_field_headers(): @pytest.mark.asyncio async def test_list_knowledge_bases_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +612,6 @@ async def test_list_knowledge_bases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.ListKnowledgeBasesResponse() ) - await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -602,7 +625,7 @@ async def test_list_knowledge_bases_field_headers_async(): def test_list_knowledge_bases_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -610,7 +633,6 @@ def test_list_knowledge_bases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.ListKnowledgeBasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_knowledge_bases(parent="parent_value",) @@ -619,12 +641,11 @@ def test_list_knowledge_bases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -636,7 +657,9 @@ def test_list_knowledge_bases_flattened_error(): @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -656,13 +679,14 @@ async def test_list_knowledge_bases_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -673,7 +697,7 @@ async def test_list_knowledge_bases_flattened_error_async(): def test_list_knowledge_bases_pager(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +743,7 @@ def test_list_knowledge_bases_pager(): def test_list_knowledge_bases_pages(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -757,7 +781,7 @@ def test_list_knowledge_bases_pages(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -802,7 +826,7 @@ async def test_list_knowledge_bases_async_pager(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -846,7 +870,7 @@ def test_get_knowledge_base( transport: str = "grpc", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -863,23 +887,17 @@ def test_get_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -891,7 +909,7 @@ def test_get_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -901,7 +919,6 @@ def test_get_knowledge_base_empty_call(): client.get_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() @@ -910,7 +927,7 @@ async def test_get_knowledge_base_async( transport: str = "grpc_asyncio", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -929,22 +946,17 @@ async def test_get_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -954,11 +966,12 @@ async def test_get_knowledge_base_async_from_dict(): def test_get_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -966,7 +979,6 @@ def test_get_knowledge_base_field_headers(): type(client.transport.get_knowledge_base), "__call__" ) as call: call.return_value = knowledge_base.KnowledgeBase() - client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -981,11 +993,14 @@ def test_get_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_get_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -995,7 +1010,6 @@ async def test_get_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.KnowledgeBase() ) - await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1009,7 +1023,7 @@ async def test_get_knowledge_base_field_headers_async(): def test_get_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1017,7 +1031,6 @@ def test_get_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_knowledge_base(name="name_value",) @@ -1026,12 +1039,11 @@ def test_get_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1043,7 +1055,9 @@ def test_get_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1063,13 +1077,14 @@ async def test_get_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1083,7 +1098,7 @@ def test_create_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,23 +1115,17 @@ def test_create_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1128,7 +1137,7 @@ def test_create_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1138,7 +1147,6 @@ def test_create_knowledge_base_empty_call(): client.create_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() @@ -1148,7 +1156,7 @@ async def test_create_knowledge_base_async( request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1167,22 +1175,17 @@ async def test_create_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1192,11 +1195,12 @@ async def test_create_knowledge_base_async_from_dict(): def test_create_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1204,7 +1208,6 @@ def test_create_knowledge_base_field_headers(): type(client.transport.create_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1219,11 +1222,14 @@ def test_create_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_create_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1233,7 +1239,6 @@ async def test_create_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1247,7 +1252,7 @@ async def test_create_knowledge_base_field_headers_async(): def test_create_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1255,7 +1260,6 @@ def test_create_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_knowledge_base( @@ -1267,16 +1271,14 @@ def test_create_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1290,7 +1292,9 @@ def test_create_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,9 +1317,7 @@ async def test_create_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) @@ -1323,7 +1325,9 @@ async def test_create_knowledge_base_flattened_async(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1343,7 @@ def test_delete_knowledge_base( transport: str = "grpc", request_type=knowledge_base.DeleteKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1352,13 +1356,11 @@ def test_delete_knowledge_base( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1373,7 +1375,7 @@ def test_delete_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1383,7 +1385,6 @@ def test_delete_knowledge_base_empty_call(): client.delete_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() @@ -1393,7 +1394,7 @@ async def test_delete_knowledge_base_async( request_type=knowledge_base.DeleteKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1406,13 +1407,11 @@ async def test_delete_knowledge_base_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1425,11 +1424,12 @@ async def test_delete_knowledge_base_async_from_dict(): def test_delete_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1437,7 +1437,6 @@ def test_delete_knowledge_base_field_headers(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = None - client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1452,11 +1451,14 @@ def test_delete_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_delete_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1464,7 +1466,6 @@ async def test_delete_knowledge_base_field_headers_async(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1478,7 +1479,7 @@ async def test_delete_knowledge_base_field_headers_async(): def test_delete_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1486,7 +1487,6 @@ def test_delete_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_knowledge_base(name="name_value",) @@ -1495,12 +1495,11 @@ def test_delete_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1512,7 +1511,9 @@ def test_delete_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1530,13 +1531,14 @@ async def test_delete_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1550,7 +1552,7 @@ def test_update_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1567,23 +1569,17 @@ def test_update_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1595,7 +1591,7 @@ def test_update_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1605,7 +1601,6 @@ def test_update_knowledge_base_empty_call(): client.update_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() @@ -1615,7 +1610,7 @@ async def test_update_knowledge_base_async( request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1634,22 +1629,17 @@ async def test_update_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1659,11 +1649,12 @@ async def test_update_knowledge_base_async_from_dict(): def test_update_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1671,7 +1662,6 @@ def test_update_knowledge_base_field_headers(): type(client.transport.update_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1689,11 +1679,14 @@ def test_update_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_update_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1703,7 +1696,6 @@ async def test_update_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1720,7 +1712,7 @@ async def test_update_knowledge_base_field_headers_async(): def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1728,28 +1720,25 @@ def test_update_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1757,13 +1746,15 @@ def test_update_knowledge_base_flattened_error(): client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1779,24 +1770,24 @@ async def test_update_knowledge_base_flattened_async(): # using the keyword arguments to the method. response = await client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1804,23 +1795,23 @@ async def test_update_knowledge_base_flattened_error_async(): await client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1830,7 +1821,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1841,7 +1832,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = KnowledgeBasesClient(transport=transport) assert client.transport is transport @@ -1850,13 +1841,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1871,23 +1862,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.KnowledgeBasesGrpcTransport,) def test_knowledge_bases_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1899,7 +1890,7 @@ def test_knowledge_bases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1916,15 +1907,40 @@ def test_knowledge_bases_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1940,19 +1956,36 @@ def test_knowledge_bases_base_transport_with_credentials_file(): def test_knowledge_bases_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) KnowledgeBasesClient() adc.assert_called_once_with( scopes=( @@ -1963,14 +1996,44 @@ def test_knowledge_bases_auth_adc(): ) -def test_knowledge_bases_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.KnowledgeBasesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1980,6 +2043,121 @@ def test_knowledge_bases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1988,7 +2166,7 @@ def test_knowledge_bases_transport_auth_adc(): ], ) def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2030,7 +2208,7 @@ def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_cl def test_knowledge_bases_host_no_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2040,7 +2218,7 @@ def test_knowledge_bases_host_no_port(): def test_knowledge_bases_host_with_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2096,9 +2274,9 @@ def test_knowledge_bases_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2181,7 +2359,6 @@ def test_knowledge_bases_transport_channel_mtls_with_adc(transport_class): def test_knowledge_base_path(): project = "squid" knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2203,7 +2380,6 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2224,7 +2400,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = KnowledgeBasesClient.common_folder_path(folder) assert expected == actual @@ -2243,7 +2418,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = KnowledgeBasesClient.common_organization_path(organization) assert expected == actual @@ -2262,7 +2436,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = KnowledgeBasesClient.common_project_path(project) assert expected == actual @@ -2282,7 +2455,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2309,7 +2481,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.KnowledgeBasesTransport, "_prep_wrapped_messages" ) as prep: client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2318,6 +2490,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = KnowledgeBasesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_participants.py b/tests/unit/gapic/dialogflow_v2/test_participants.py index bef06db64..a16cb1c98 100644 --- a/tests/unit/gapic/dialogflow_v2/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2/test_participants.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,18 +23,24 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.participants import ParticipantsAsyncClient from google.cloud.dialogflow_v2.services.participants import ParticipantsClient from google.cloud.dialogflow_v2.services.participants import pagers from google.cloud.dialogflow_v2.services.participants import transports +from google.cloud.dialogflow_v2.services.participants.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.participants.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import entity_type @@ -44,9 +49,33 @@ from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_participants_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -158,7 +187,7 @@ def test_participants_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ParticipantsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -442,7 +471,7 @@ def test_create_participant( transport: str = "grpc", request_type=gcd_participant.CreateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -459,23 +488,17 @@ def test_create_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -487,7 +510,7 @@ def test_create_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -497,7 +520,6 @@ def test_create_participant_empty_call(): client.create_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() @@ -507,7 +529,7 @@ async def test_create_participant_async( request_type=gcd_participant.CreateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,22 +548,17 @@ async def test_create_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -551,11 +568,12 @@ async def test_create_participant_async_from_dict(): def test_create_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -563,7 +581,6 @@ def test_create_participant_field_headers(): type(client.transport.create_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -578,11 +595,12 @@ def test_create_participant_field_headers(): @pytest.mark.asyncio async def test_create_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -592,7 +610,6 @@ async def test_create_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -606,7 +623,7 @@ async def test_create_participant_field_headers_async(): def test_create_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -614,7 +631,6 @@ def test_create_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_participant( @@ -626,14 +642,12 @@ def test_create_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") def test_create_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -647,7 +661,7 @@ def test_create_participant_flattened_error(): @pytest.mark.asyncio async def test_create_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -670,15 +684,13 @@ async def test_create_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") @pytest.mark.asyncio async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -694,7 +706,7 @@ def test_get_participant( transport: str = "grpc", request_type=participant.GetParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -709,23 +721,17 @@ def test_get_participant( role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -737,7 +743,7 @@ def test_get_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -745,7 +751,6 @@ def test_get_participant_empty_call(): client.get_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() @@ -754,7 +759,7 @@ async def test_get_participant_async( transport: str = "grpc_asyncio", request_type=participant.GetParticipantRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -771,22 +776,17 @@ async def test_get_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -796,17 +796,17 @@ async def test_get_participant_async_from_dict(): def test_get_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: call.return_value = participant.Participant() - client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -821,11 +821,12 @@ def test_get_participant_field_headers(): @pytest.mark.asyncio async def test_get_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -833,7 +834,6 @@ async def test_get_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.Participant() ) - await client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -847,13 +847,12 @@ async def test_get_participant_field_headers_async(): def test_get_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_participant(name="name_value",) @@ -862,12 +861,11 @@ def test_get_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -879,7 +877,7 @@ def test_get_participant_flattened_error(): @pytest.mark.asyncio async def test_get_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: @@ -897,13 +895,12 @@ async def test_get_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -917,7 +914,7 @@ def test_list_participants( transport: str = "grpc", request_type=participant.ListParticipantsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -932,19 +929,15 @@ def test_list_participants( call.return_value = participant.ListParticipantsResponse( next_page_token="next_page_token_value", ) - response = client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == "next_page_token_value" @@ -956,7 +949,7 @@ def test_list_participants_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -966,7 +959,6 @@ def test_list_participants_empty_call(): client.list_participants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() @@ -975,7 +967,7 @@ async def test_list_participants_async( transport: str = "grpc_asyncio", request_type=participant.ListParticipantsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -992,18 +984,15 @@ async def test_list_participants_async( next_page_token="next_page_token_value", ) ) - response = await client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListParticipantsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1013,11 +1002,12 @@ async def test_list_participants_async_from_dict(): def test_list_participants_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1025,7 +1015,6 @@ def test_list_participants_field_headers(): type(client.transport.list_participants), "__call__" ) as call: call.return_value = participant.ListParticipantsResponse() - client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1040,11 +1029,12 @@ def test_list_participants_field_headers(): @pytest.mark.asyncio async def test_list_participants_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1054,7 +1044,6 @@ async def test_list_participants_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListParticipantsResponse() ) - await client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1068,7 +1057,7 @@ async def test_list_participants_field_headers_async(): def test_list_participants_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1076,7 +1065,6 @@ def test_list_participants_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.ListParticipantsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_participants(parent="parent_value",) @@ -1085,12 +1073,11 @@ def test_list_participants_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_participants_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1102,7 +1089,7 @@ def test_list_participants_flattened_error(): @pytest.mark.asyncio async def test_list_participants_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1122,13 +1109,12 @@ async def test_list_participants_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_participants_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1139,7 +1125,7 @@ async def test_list_participants_flattened_error_async(): def test_list_participants_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1181,7 +1167,7 @@ def test_list_participants_pager(): def test_list_participants_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1215,7 +1201,7 @@ def test_list_participants_pages(): @pytest.mark.asyncio async def test_list_participants_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1256,7 +1242,7 @@ async def test_list_participants_async_pager(): @pytest.mark.asyncio async def test_list_participants_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1296,7 +1282,7 @@ def test_update_participant( transport: str = "grpc", request_type=gcd_participant.UpdateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1313,23 +1299,17 @@ def test_update_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -1341,7 +1321,7 @@ def test_update_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1351,7 +1331,6 @@ def test_update_participant_empty_call(): client.update_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() @@ -1361,7 +1340,7 @@ async def test_update_participant_async( request_type=gcd_participant.UpdateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1380,22 +1359,17 @@ async def test_update_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -1405,11 +1379,12 @@ async def test_update_participant_async_from_dict(): def test_update_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1417,7 +1392,6 @@ def test_update_participant_field_headers(): type(client.transport.update_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1434,11 +1408,12 @@ def test_update_participant_field_headers(): @pytest.mark.asyncio async def test_update_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1448,7 +1423,6 @@ async def test_update_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1464,7 +1438,7 @@ async def test_update_participant_field_headers_async(): def test_update_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1472,26 +1446,23 @@ def test_update_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_participant( participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == gcd_participant.Participant(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1499,13 +1470,13 @@ def test_update_participant_flattened_error(): client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1521,22 +1492,20 @@ async def test_update_participant_flattened_async(): # using the keyword arguments to the method. response = await client.update_participant( participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == gcd_participant.Participant(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1544,7 +1513,7 @@ async def test_update_participant_flattened_error_async(): await client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1552,7 +1521,7 @@ def test_analyze_content( transport: str = "grpc", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1565,19 +1534,15 @@ def test_analyze_content( call.return_value = gcd_participant.AnalyzeContentResponse( reply_text="reply_text_value", ) - response = client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1589,7 +1554,7 @@ def test_analyze_content_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1597,7 +1562,6 @@ def test_analyze_content_empty_call(): client.analyze_content() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() @@ -1606,7 +1570,7 @@ async def test_analyze_content_async( transport: str = "grpc_asyncio", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1619,18 +1583,15 @@ async def test_analyze_content_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse(reply_text="reply_text_value",) ) - response = await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1640,17 +1601,17 @@ async def test_analyze_content_async_from_dict(): def test_analyze_content_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: call.return_value = gcd_participant.AnalyzeContentResponse() - client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1665,11 +1626,12 @@ def test_analyze_content_field_headers(): @pytest.mark.asyncio async def test_analyze_content_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1677,7 +1639,6 @@ async def test_analyze_content_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse() ) - await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1691,13 +1652,12 @@ async def test_analyze_content_field_headers_async(): def test_analyze_content_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.AnalyzeContentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_content( @@ -1710,14 +1670,12 @@ def test_analyze_content_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") def test_analyze_content_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1732,7 +1690,7 @@ def test_analyze_content_flattened_error(): @pytest.mark.asyncio async def test_analyze_content_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: @@ -1754,15 +1712,13 @@ async def test_analyze_content_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") @pytest.mark.asyncio async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1779,7 +1735,7 @@ def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1792,21 +1748,16 @@ def test_suggest_articles( call.return_value = participant.SuggestArticlesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1818,7 +1769,7 @@ def test_suggest_articles_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1826,7 +1777,6 @@ def test_suggest_articles_empty_call(): client.suggest_articles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() @@ -1835,7 +1785,7 @@ async def test_suggest_articles_async( transport: str = "grpc_asyncio", request_type=participant.SuggestArticlesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1850,20 +1800,16 @@ async def test_suggest_articles_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1873,17 +1819,17 @@ async def test_suggest_articles_async_from_dict(): def test_suggest_articles_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: call.return_value = participant.SuggestArticlesResponse() - client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1898,11 +1844,12 @@ def test_suggest_articles_field_headers(): @pytest.mark.asyncio async def test_suggest_articles_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1910,7 +1857,6 @@ async def test_suggest_articles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestArticlesResponse() ) - await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1924,13 +1870,12 @@ async def test_suggest_articles_field_headers_async(): def test_suggest_articles_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestArticlesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_articles(parent="parent_value",) @@ -1939,12 +1884,11 @@ def test_suggest_articles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_articles_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1956,7 +1900,7 @@ def test_suggest_articles_flattened_error(): @pytest.mark.asyncio async def test_suggest_articles_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: @@ -1974,13 +1918,12 @@ async def test_suggest_articles_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1994,7 +1937,7 @@ def test_suggest_faq_answers( transport: str = "grpc", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2009,21 +1952,16 @@ def test_suggest_faq_answers( call.return_value = participant.SuggestFaqAnswersResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2035,7 +1973,7 @@ def test_suggest_faq_answers_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2045,7 +1983,6 @@ def test_suggest_faq_answers_empty_call(): client.suggest_faq_answers() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() @@ -2054,7 +1991,7 @@ async def test_suggest_faq_answers_async( transport: str = "grpc_asyncio", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2071,20 +2008,16 @@ async def test_suggest_faq_answers_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2094,11 +2027,12 @@ async def test_suggest_faq_answers_async_from_dict(): def test_suggest_faq_answers_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2106,7 +2040,6 @@ def test_suggest_faq_answers_field_headers(): type(client.transport.suggest_faq_answers), "__call__" ) as call: call.return_value = participant.SuggestFaqAnswersResponse() - client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2121,11 +2054,12 @@ def test_suggest_faq_answers_field_headers(): @pytest.mark.asyncio async def test_suggest_faq_answers_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2135,7 +2069,6 @@ async def test_suggest_faq_answers_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestFaqAnswersResponse() ) - await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2149,7 +2082,7 @@ async def test_suggest_faq_answers_field_headers_async(): def test_suggest_faq_answers_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2157,7 +2090,6 @@ def test_suggest_faq_answers_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestFaqAnswersResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_faq_answers(parent="parent_value",) @@ -2166,12 +2098,11 @@ def test_suggest_faq_answers_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2183,7 +2114,7 @@ def test_suggest_faq_answers_flattened_error(): @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2203,13 +2134,12 @@ async def test_suggest_faq_answers_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2222,16 +2152,16 @@ async def test_suggest_faq_answers_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2241,7 +2171,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2252,7 +2182,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ParticipantsClient(transport=transport) assert client.transport is transport @@ -2261,13 +2191,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2282,23 +2212,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ParticipantsGrpcTransport,) def test_participants_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2310,7 +2240,7 @@ def test_participants_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2329,15 +2259,40 @@ def test_participants_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_participants_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2353,19 +2308,36 @@ def test_participants_base_transport_with_credentials_file(): def test_participants_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_participants_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ParticipantsClient() adc.assert_called_once_with( scopes=( @@ -2376,14 +2348,44 @@ def test_participants_auth_adc(): ) -def test_participants_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ParticipantsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2393,12 +2395,127 @@ def test_participants_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport], ) def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2440,7 +2557,7 @@ def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class def test_participants_host_no_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2450,7 +2567,7 @@ def test_participants_host_no_port(): def test_participants_host_with_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2501,9 +2618,9 @@ def test_participants_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2584,7 +2701,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2608,7 +2724,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2632,7 +2747,6 @@ def test_message_path(): project = "scallop" conversation = "abalone" message = "squid" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2657,7 +2771,6 @@ def test_participant_path(): project = "oyster" conversation = "nudibranch" participant = "cuttlefish" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format( project=project, conversation=conversation, participant=participant, ) @@ -2682,7 +2795,6 @@ def test_session_entity_type_path(): project = "scallop" session = "abalone" entity_type = "squid" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2705,7 +2817,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2726,7 +2837,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = ParticipantsClient.common_folder_path(folder) assert expected == actual @@ -2745,7 +2855,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = ParticipantsClient.common_organization_path(organization) assert expected == actual @@ -2764,7 +2873,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = ParticipantsClient.common_project_path(project) assert expected == actual @@ -2784,7 +2892,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2811,7 +2918,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ParticipantsTransport, "_prep_wrapped_messages" ) as prep: client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2820,6 +2927,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ParticipantsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py b/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py index 611435246..9762142db 100644 --- a/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) from google.cloud.dialogflow_v2.services.session_entity_types import pagers from google.cloud.dialogflow_v2.services.session_entity_types import transports +from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import session_entity_type from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_session_entity_type, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_session_entity_types_client_from_service_account_info(client_class): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_session_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionEntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -467,7 +496,7 @@ def test_list_session_entity_types( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,19 +511,15 @@ def test_list_session_entity_types( call.return_value = session_entity_type.ListSessionEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -506,7 +531,7 @@ def test_list_session_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -516,7 +541,6 @@ def test_list_session_entity_types_empty_call(): client.list_session_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() @@ -526,7 +550,7 @@ async def test_list_session_entity_types_async( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,18 +567,15 @@ async def test_list_session_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -564,11 +585,14 @@ async def test_list_session_entity_types_async_from_dict(): def test_list_session_entity_types_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -576,7 +600,6 @@ def test_list_session_entity_types_field_headers(): type(client.transport.list_session_entity_types), "__call__" ) as call: call.return_value = session_entity_type.ListSessionEntityTypesResponse() - client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -592,12 +615,13 @@ def test_list_session_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_session_entity_types_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -607,7 +631,6 @@ async def test_list_session_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.ListSessionEntityTypesResponse() ) - await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -621,7 +644,9 @@ async def test_list_session_entity_types_field_headers_async(): def test_list_session_entity_types_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -629,7 +654,6 @@ def test_list_session_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.ListSessionEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_session_entity_types(parent="parent_value",) @@ -638,12 +662,13 @@ def test_list_session_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +681,7 @@ def test_list_session_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_session_entity_types_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -677,14 +702,13 @@ async def test_list_session_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_session_entity_types_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -696,7 +720,7 @@ async def test_list_session_entity_types_flattened_error_async(): def test_list_session_entity_types_pager(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +768,7 @@ def test_list_session_entity_types_pager(): def test_list_session_entity_types_pages(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -783,7 +807,7 @@ def test_list_session_entity_types_pages(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pager(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +856,7 @@ async def test_list_session_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pages(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -878,7 +902,7 @@ def test_get_session_entity_type( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -894,21 +918,16 @@ def test_get_session_entity_type( name="name_value", entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -923,7 +942,7 @@ def test_get_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -933,7 +952,6 @@ def test_get_session_entity_type_empty_call(): client.get_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() @@ -943,7 +961,7 @@ async def test_get_session_entity_type_async( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -961,20 +979,16 @@ async def test_get_session_entity_type_async( entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -987,11 +1001,14 @@ async def test_get_session_entity_type_async_from_dict(): def test_get_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -999,7 +1016,6 @@ def test_get_session_entity_type_field_headers(): type(client.transport.get_session_entity_type), "__call__" ) as call: call.return_value = session_entity_type.SessionEntityType() - client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1015,12 +1031,13 @@ def test_get_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1030,7 +1047,6 @@ async def test_get_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.SessionEntityType() ) - await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1044,7 +1060,9 @@ async def test_get_session_entity_type_field_headers_async(): def test_get_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1052,7 +1070,6 @@ def test_get_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_session_entity_type(name="name_value",) @@ -1061,12 +1078,13 @@ def test_get_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1079,7 +1097,7 @@ def test_get_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,14 +1118,13 @@ async def test_get_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1123,7 +1140,7 @@ def test_create_session_entity_type( request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1139,21 +1156,16 @@ def test_create_session_entity_type( name="name_value", entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1168,7 +1180,7 @@ def test_create_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1178,7 +1190,6 @@ def test_create_session_entity_type_empty_call(): client.create_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1206,20 +1217,16 @@ async def test_create_session_entity_type_async( entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1232,11 +1239,14 @@ async def test_create_session_entity_type_async_from_dict(): def test_create_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1244,7 +1254,6 @@ def test_create_session_entity_type_field_headers(): type(client.transport.create_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1260,12 +1269,13 @@ def test_create_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1275,7 +1285,6 @@ async def test_create_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1289,7 +1298,9 @@ async def test_create_session_entity_type_field_headers_async(): def test_create_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1297,7 +1308,6 @@ def test_create_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_session_entity_type( @@ -1311,16 +1321,16 @@ def test_create_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1347,7 @@ def test_create_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1363,9 +1373,7 @@ async def test_create_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) @@ -1374,7 +1382,7 @@ async def test_create_session_entity_type_flattened_async(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1394,7 +1402,7 @@ def test_update_session_entity_type( request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1410,21 +1418,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1439,7 +1442,7 @@ def test_update_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1449,7 +1452,6 @@ def test_update_session_entity_type_empty_call(): client.update_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1459,7 +1461,7 @@ async def test_update_session_entity_type_async( request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1477,20 +1479,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1503,11 +1501,14 @@ async def test_update_session_entity_type_async_from_dict(): def test_update_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1516,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1534,12 +1534,13 @@ def test_update_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1549,7 +1550,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1566,7 +1566,9 @@ async def test_update_session_entity_type_field_headers_async(): def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1574,30 +1576,29 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_session_entity_type( session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1607,14 +1608,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,25 +1634,23 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1662,7 +1661,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1671,7 +1670,7 @@ def test_delete_session_entity_type( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1684,13 +1683,11 @@ def test_delete_session_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1705,7 +1702,7 @@ def test_delete_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1715,7 +1712,6 @@ def test_delete_session_entity_type_empty_call(): client.delete_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() @@ -1725,7 +1721,7 @@ async def test_delete_session_entity_type_async( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1738,13 +1734,11 @@ async def test_delete_session_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1757,11 +1751,14 @@ async def test_delete_session_entity_type_async_from_dict(): def test_delete_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1769,7 +1766,6 @@ def test_delete_session_entity_type_field_headers(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = None - client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1785,12 +1781,13 @@ def test_delete_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1798,7 +1795,6 @@ async def test_delete_session_entity_type_field_headers_async(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1812,7 +1808,9 @@ async def test_delete_session_entity_type_field_headers_async(): def test_delete_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1820,7 +1818,6 @@ def test_delete_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_session_entity_type(name="name_value",) @@ -1829,12 +1826,13 @@ def test_delete_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1847,7 +1845,7 @@ def test_delete_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1866,14 +1864,13 @@ async def test_delete_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1887,16 +1884,16 @@ async def test_delete_session_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1906,7 +1903,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1917,7 +1914,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionEntityTypesClient(transport=transport) assert client.transport is transport @@ -1926,13 +1923,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1947,23 +1944,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.SessionEntityTypesGrpcTransport,) def test_session_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1975,7 +1974,7 @@ def test_session_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1992,15 +1991,40 @@ def test_session_entity_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_session_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2016,19 +2040,36 @@ def test_session_entity_types_base_transport_with_credentials_file(): def test_session_entity_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_session_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SessionEntityTypesClient() adc.assert_called_once_with( scopes=( @@ -2039,14 +2080,44 @@ def test_session_entity_types_auth_adc(): ) -def test_session_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionEntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2056,6 +2127,121 @@ def test_session_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2066,7 +2252,7 @@ def test_session_entity_types_transport_auth_adc(): def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2108,7 +2294,7 @@ def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( def test_session_entity_types_host_no_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2118,7 +2304,7 @@ def test_session_entity_types_host_no_port(): def test_session_entity_types_host_with_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2174,9 +2360,9 @@ def test_session_entity_types_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2260,7 +2446,6 @@ def test_session_entity_type_path(): project = "squid" session = "clam" entity_type = "whelk" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2285,7 +2470,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2306,7 +2490,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2325,7 +2508,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2344,7 +2526,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2364,7 +2545,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2391,7 +2571,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionEntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2400,6 +2580,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionEntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_sessions.py b/tests/unit/gapic/dialogflow_v2/test_sessions.py index 8b119b26a..1b64d632c 100644 --- a/tests/unit/gapic/dialogflow_v2/test_sessions.py +++ b/tests/unit/gapic/dialogflow_v2/test_sessions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,17 +23,23 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2.services.sessions import SessionsAsyncClient from google.cloud.dialogflow_v2.services.sessions import SessionsClient from google.cloud.dialogflow_v2.services.sessions import transports +from google.cloud.dialogflow_v2.services.sessions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.sessions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import entity_type @@ -42,10 +47,34 @@ from google.cloud.dialogflow_v2.types import session as gcd_session from google.cloud.dialogflow_v2.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -89,7 +118,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -104,7 +133,7 @@ def test_sessions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -149,7 +178,7 @@ def test_sessions_client_get_transport_class(): def test_sessions_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -425,7 +454,7 @@ def test_detect_intent( transport: str = "grpc", request_type=gcd_session.DetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -438,21 +467,16 @@ def test_detect_intent( call.return_value = gcd_session.DetectIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -464,7 +488,7 @@ def test_detect_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -472,7 +496,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() @@ -481,7 +504,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=gcd_session.DetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -496,20 +519,16 @@ async def test_detect_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -519,17 +538,17 @@ async def test_detect_intent_async_from_dict(): def test_detect_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: call.return_value = gcd_session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -544,11 +563,12 @@ def test_detect_intent_field_headers(): @pytest.mark.asyncio async def test_detect_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -556,7 +576,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -570,13 +589,12 @@ async def test_detect_intent_field_headers_async(): def test_detect_intent_flattened(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_session.DetectIntentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_intent( @@ -592,9 +610,7 @@ def test_detect_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -603,7 +619,7 @@ def test_detect_intent_flattened(): def test_detect_intent_flattened_error(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -621,7 +637,7 @@ def test_detect_intent_flattened_error(): @pytest.mark.asyncio async def test_detect_intent_flattened_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: @@ -646,9 +662,7 @@ async def test_detect_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -658,7 +672,7 @@ async def test_detect_intent_flattened_async(): @pytest.mark.asyncio async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -678,13 +692,12 @@ def test_streaming_detect_intent( transport: str = "grpc", request_type=session.StreamingDetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -693,13 +706,11 @@ def test_streaming_detect_intent( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([session.StreamingDetectIntentResponse()]) - response = client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -716,13 +727,12 @@ async def test_streaming_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.StreamingDetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -734,13 +744,11 @@ async def test_streaming_detect_intent_async( call.return_value.read = mock.AsyncMock( side_effect=[session.StreamingDetectIntentResponse()] ) - response = await client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -756,16 +764,16 @@ async def test_streaming_detect_intent_async_from_dict(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -775,7 +783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -786,7 +794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionsClient(transport=transport) assert client.transport is transport @@ -795,13 +803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -813,23 +821,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SessionsGrpcTransport,) def test_sessions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -841,7 +849,7 @@ def test_sessions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -855,15 +863,40 @@ def test_sessions_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_sessions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -879,19 +912,36 @@ def test_sessions_base_transport_with_credentials_file(): def test_sessions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_sessions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SessionsClient() adc.assert_called_once_with( scopes=( @@ -902,14 +952,38 @@ def test_sessions_auth_adc(): ) -def test_sessions_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_sessions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_sessions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -919,12 +993,123 @@ def test_sessions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport], ) def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -966,7 +1151,7 @@ def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_sessions_host_no_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -976,7 +1161,7 @@ def test_sessions_host_no_port(): def test_sessions_host_with_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1027,9 +1212,9 @@ def test_sessions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1110,7 +1295,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -1134,7 +1318,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -1157,7 +1340,6 @@ def test_parse_intent_path(): def test_session_path(): project = "scallop" session = "abalone" - expected = "projects/{project}/agent/sessions/{session}".format( project=project, session=session, ) @@ -1181,7 +1363,6 @@ def test_session_entity_type_path(): project = "whelk" session = "octopus" entity_type = "oyster" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -1204,7 +1385,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1225,7 +1405,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1244,7 +1423,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1263,7 +1441,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1283,7 +1460,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1310,7 +1486,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionsTransport, "_prep_wrapped_messages" ) as prep: client = SessionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1319,6 +1495,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py b/tests/unit/gapic/dialogflow_v2/test_versions.py similarity index 67% rename from owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py rename to tests/unit/gapic/dialogflow_v2/test_versions.py index 9bfb7a9a8..76220dfc5 100644 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py +++ b/tests/unit/gapic/dialogflow_v2/test_versions.py @@ -35,8 +35,12 @@ from google.cloud.dialogflow_v2.services.versions import VersionsClient from google.cloud.dialogflow_v2.services.versions import pagers from google.cloud.dialogflow_v2.services.versions import transports -from google.cloud.dialogflow_v2.services.versions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2.services.versions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.versions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import version from google.cloud.dialogflow_v2.types import version as gcd_version from google.oauth2 import service_account @@ -67,6 +71,7 @@ reason="This test requires google-api-core >= 1.26.0", ) + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -75,7 +80,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -87,35 +96,42 @@ def test__get_default_mtls_endpoint(): 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(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds @@ -125,7 +141,7 @@ def test_versions_client_from_service_account_file(client_class): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_versions_client_get_transport_class(): @@ -139,29 +155,36 @@ def test_versions_client_get_transport_class(): assert transport == transports.VersionsGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) def test_versions_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + 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: + 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -177,7 +200,7 @@ def test_versions_client_client_options(client_class, transport_class, transport # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -193,7 +216,7 @@ def test_versions_client_client_options(client_class, transport_class, transport # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -213,13 +236,15 @@ def test_versions_client_client_options(client_class, transport_class, transport client = client_class() # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class() # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -232,24 +257,50 @@ def test_versions_client_client_options(client_class, transport_class, transport client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +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: + 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) @@ -272,10 +323,18 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ # 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): + 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 @@ -296,9 +355,14 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -312,16 +376,19 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -334,16 +401,20 @@ def test_versions_client_client_options_scopes(client_class, transport_class, tr client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_credentials_file( + client_class, transport_class, transport_name +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -358,11 +429,11 @@ def test_versions_client_client_options_credentials_file(client_class, transport def test_versions_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + 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'} - ) + client = VersionsClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -374,10 +445,11 @@ def test_versions_client_client_options_from_dict(): ) -def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): +def test_list_versions( + transport: str = "grpc", request_type=version.ListVersionsRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -385,12 +457,10 @@ def test_list_versions(transport: str = 'grpc', request_type=version.ListVersion 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: + 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', + next_page_token="next_page_token_value", ) response = client.list_versions(request) @@ -401,7 +471,7 @@ def test_list_versions(transport: str = 'grpc', request_type=version.ListVersion # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_versions_from_dict(): @@ -412,14 +482,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: client.list_versions() call.assert_called() _, args, _ = call.mock_calls[0] @@ -427,10 +494,11 @@ def test_list_versions_empty_call(): @pytest.mark.asyncio -async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): +async def test_list_versions_async( + transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -438,13 +506,11 @@ async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type 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: + 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', - )) + 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. @@ -454,7 +520,7 @@ async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio @@ -463,20 +529,16 @@ async def test_list_versions_async_from_dict(): def test_list_versions_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.ListVersionsRequest() - request.parent = 'parent/value' + 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: + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: call.return_value = version.ListVersionsResponse() client.list_versions(request) @@ -487,29 +549,24 @@ def test_list_versions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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()) + 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. @@ -519,135 +576,97 @@ async def test_list_versions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_list_versions_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', - ) + client.list_versions(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' + assert args[0].parent == "parent_value" def test_list_versions_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.ListVersionsRequest(), parent="parent_value", ) @pytest.mark.asyncio async def test_list_versions_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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.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', - ) + response = await client.list_versions(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' + assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_versions_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.ListVersionsRequest(), parent="parent_value", ) def test_list_versions_pager(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_versions(request={}) @@ -655,146 +674,100 @@ def test_list_versions_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) + assert all(isinstance(i, version.Version) for i in results) + def test_list_versions_pages(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) pages = list(client.list_versions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + 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, - ) + 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: + 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', + 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', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) async_pager = await client.list_versions(request={},) - assert async_pager.next_page_token == 'abc' + assert async_pager.next_page_token == "abc" responses = [] async for response in async_pager: responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, version.Version) - for i in responses) + 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, - ) + 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: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) pages = [] async for page_ in (await client.list_versions(request={})).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + +def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,13 +775,11 @@ def test_get_version(transport: str = 'grpc', request_type=version.GetVersionReq 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=version.Version.VersionStatus.IN_PROGRESS, ) @@ -821,8 +792,8 @@ def test_get_version(transport: str = 'grpc', request_type=version.GetVersionReq # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == version.Version.VersionStatus.IN_PROGRESS @@ -835,14 +806,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.get_version), "__call__") as call: client.get_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -850,10 +818,11 @@ def test_get_version_empty_call(): @pytest.mark.asyncio -async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): +async def test_get_version_async( + transport: str = "grpc_asyncio", request_type=version.GetVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -861,16 +830,16 @@ async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=v 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: + 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, - )) + 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. @@ -880,8 +849,8 @@ async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=v # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == version.Version.VersionStatus.IN_PROGRESS @@ -892,20 +861,16 @@ async def test_get_version_async_from_dict(): def test_get_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.GetVersionRequest() - request.name = 'name/value' + 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: + with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = version.Version() client.get_version(request) @@ -916,28 +881,21 @@ def test_get_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -948,96 +906,76 @@ async def test_get_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: + 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', - ) + client.get_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_get_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.GetVersionRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_version_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: + 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', - ) + response = await client.get_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.GetVersionRequest(), name="name_value", ) -def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): +def test_create_version( + transport: str = "grpc", request_type=gcd_version.CreateVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1045,13 +983,11 @@ def test_create_version(transport: str = 'grpc', request_type=gcd_version.Create 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=gcd_version.Version.VersionStatus.IN_PROGRESS, ) @@ -1064,8 +1000,8 @@ def test_create_version(transport: str = 'grpc', request_type=gcd_version.Create # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1078,14 +1014,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.create_version), "__call__") as call: client.create_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1093,10 +1026,11 @@ def test_create_version_empty_call(): @pytest.mark.asyncio -async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): +async def test_create_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.CreateVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1104,16 +1038,16 @@ async def test_create_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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, - )) + 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. @@ -1123,8 +1057,8 @@ async def test_create_version_async(transport: str = 'grpc_asyncio', request_typ # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1135,20 +1069,16 @@ async def test_create_version_async_from_dict(): def test_create_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.CreateVersionRequest() - request.parent = 'parent/value' + 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: + with mock.patch.object(type(client.transport.create_version), "__call__") as call: call.return_value = gcd_version.Version() client.create_version(request) @@ -1159,28 +1089,21 @@ def test_create_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -1191,63 +1114,49 @@ async def test_create_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_create_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: + 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'), + parent="parent_value", version=gcd_version.Version(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") def test_create_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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'), + 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(), - ) + 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: + 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() @@ -1255,38 +1164,36 @@ async def test_create_version_flattened_async(): # 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'), + parent="parent_value", version=gcd_version.Version(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") @pytest.mark.asyncio async def test_create_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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'), + parent="parent_value", + version=gcd_version.Version(name="name_value"), ) -def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): +def test_update_version( + transport: str = "grpc", request_type=gcd_version.UpdateVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1294,13 +1201,11 @@ def test_update_version(transport: str = 'grpc', request_type=gcd_version.Update 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=gcd_version.Version.VersionStatus.IN_PROGRESS, ) @@ -1313,8 +1218,8 @@ def test_update_version(transport: str = 'grpc', request_type=gcd_version.Update # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1327,14 +1232,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.update_version), "__call__") as call: client.update_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1342,10 +1244,11 @@ def test_update_version_empty_call(): @pytest.mark.asyncio -async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): +async def test_update_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.UpdateVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1353,16 +1256,16 @@ async def test_update_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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, - )) + 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. @@ -1372,8 +1275,8 @@ async def test_update_version_async(transport: str = 'grpc_asyncio', request_typ # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1384,20 +1287,16 @@ async def test_update_version_async_from_dict(): def test_update_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.UpdateVersionRequest() - request.version.name = 'version.name/value' + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + with mock.patch.object(type(client.transport.update_version), "__call__") as call: call.return_value = gcd_version.Version() client.update_version(request) @@ -1408,28 +1307,23 @@ def test_update_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'version.name=version.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] @pytest.mark.asyncio async def test_update_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.UpdateVersionRequest() - request.version.name = 'version.name/value' + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + 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) @@ -1440,63 +1334,52 @@ async def test_update_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'version.name=version.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] def test_update_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].version == gcd_version.Version(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + 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(), - ) + 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: + 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() @@ -1504,38 +1387,37 @@ async def test_update_version_flattened_async(): # 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].version == gcd_version.Version(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): +def test_delete_version( + transport: str = "grpc", request_type=version.DeleteVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1543,9 +1425,7 @@ def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVers 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: + 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) @@ -1567,14 +1447,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: client.delete_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1582,10 +1459,11 @@ def test_delete_version_empty_call(): @pytest.mark.asyncio -async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): +async def test_delete_version_async( + transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1593,9 +1471,7 @@ async def test_delete_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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) @@ -1615,20 +1491,16 @@ async def test_delete_version_async_from_dict(): def test_delete_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.DeleteVersionRequest() - request.name = 'name/value' + 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: + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = None client.delete_version(request) @@ -1639,28 +1511,21 @@ def test_delete_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -1671,89 +1536,68 @@ async def test_delete_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_delete_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: + 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', - ) + client.delete_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_delete_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.DeleteVersionRequest(), name="name_value", ) @pytest.mark.asyncio async def test_delete_version_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: + 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', - ) + response = await client.delete_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.DeleteVersionRequest(), name="name_value", ) @@ -1764,8 +1608,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -1784,8 +1627,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = VersionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client_options={"scopes": ["1", "2"]}, transport=transport, ) @@ -1797,6 +1639,7 @@ def test_transport_instance(): 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( @@ -1811,39 +1654,39 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VersionsGrpcTransport, - ) + 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" + 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: + 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(), @@ -1852,11 +1695,11 @@ def test_versions_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_versions', - 'get_version', - 'create_version', - 'update_version', - 'delete_version', + "list_versions", + "get_version", + "create_version", + "update_version", + "delete_version", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1866,19 +1709,23 @@ def test_versions_base_transport(): @requires_google_auth_gte_1_25_0 def test_versions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1886,16 +1733,21 @@ def test_versions_base_transport_with_credentials_file(): @requires_google_auth_lt_1_25_0 def test_versions_base_transport_with_credentials_file_old_google_auth(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), quota_project_id="octopus", ) @@ -1903,7 +1755,9 @@ def test_versions_base_transport_with_credentials_file_old_google_auth(): 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: + 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() @@ -1913,15 +1767,15 @@ def test_versions_base_transport_with_adc(): @requires_google_auth_gte_1_25_0 def test_versions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1929,42 +1783,42 @@ def test_versions_auth_adc(): @requires_google_auth_lt_1_25_0 def test_versions_auth_adc_old_google_auth(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) VersionsClient() adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + 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, - ], + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) @requires_google_auth_gte_1_25_0 def test_versions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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',), + 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) @requires_google_auth_lt_1_25_0 def test_versions_transport_auth_adc_old_google_auth(transport_class): @@ -1973,10 +1827,11 @@ def test_versions_transport_auth_adc_old_google_auth(transport_class): with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1985,22 +1840,21 @@ def test_versions_transport_auth_adc_old_google_auth(transport_class): "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_gte_1_26_0 def test_versions_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "dialogflow.googleapis.com:443", @@ -2008,9 +1862,9 @@ def test_versions_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), scopes=["1", "2"], default_host="dialogflow.googleapis.com", ssl_credentials=None, @@ -2025,14 +1879,16 @@ def test_versions_transport_create_channel(transport_class, grpc_helpers): "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 def test_versions_transport_create_channel_old_api_core(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -2045,9 +1901,9 @@ def test_versions_transport_create_channel_old_api_core(transport_class, grpc_he credentials_file=None, quota_project_id="octopus", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), @@ -2060,14 +1916,16 @@ def test_versions_transport_create_channel_old_api_core(transport_class, grpc_he "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 def test_versions_transport_create_channel_user_scopes(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -2089,10 +1947,11 @@ def test_versions_transport_create_channel_user_scopes(transport_class, grpc_hel ) -@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) -def test_versions_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@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. @@ -2101,15 +1960,15 @@ def test_versions_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, @@ -2125,37 +1984,40 @@ def test_versions_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) def test_versions_host_no_port(): client = VersionsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_versions_host_with_port(): client = VersionsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' + assert client.transport._host == "dialogflow.googleapis.com:8000" + def test_versions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2163,12 +2025,11 @@ def test_versions_grpc_transport_channel(): def test_versions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2177,12 +2038,17 @@ def test_versions_grpc_asyncio_transport_channel(): # 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: +@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 @@ -2191,7 +2057,7 @@ def test_versions_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2208,8 +2074,8 @@ def test_versions_transport_channel_mtls_with_client_cert_source( credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -2224,17 +2090,20 @@ def test_versions_transport_channel_mtls_with_client_cert_source( # 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 -): +@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: + 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() @@ -2252,8 +2121,8 @@ def test_versions_transport_channel_mtls_with_adc( credentials=mock_cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -2268,7 +2137,9 @@ def test_versions_transport_channel_mtls_with_adc( def test_version_path(): project = "squid" version = "clam" - expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + expected = "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) actual = VersionsClient.version_path(project, version) assert expected == actual @@ -2284,9 +2155,12 @@ def test_parse_version_path(): 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, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = VersionsClient.common_billing_account_path(billing_account) assert expected == actual @@ -2301,9 +2175,10 @@ def test_parse_common_billing_account_path(): actual = VersionsClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format(folder=folder,) actual = VersionsClient.common_folder_path(folder) assert expected == actual @@ -2318,9 +2193,10 @@ def test_parse_common_folder_path(): actual = VersionsClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format(organization=organization,) actual = VersionsClient.common_organization_path(organization) assert expected == actual @@ -2335,9 +2211,10 @@ def test_parse_common_organization_path(): actual = VersionsClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format(project=project,) actual = VersionsClient.common_project_path(project) assert expected == actual @@ -2352,10 +2229,13 @@ def test_parse_common_project_path(): 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, ) + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) actual = VersionsClient.common_location_path(project, location) assert expected == actual @@ -2375,17 +2255,19 @@ def test_parse_common_location_path(): def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + 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, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/__init__.py b/tests/unit/gapic/dialogflow_v2beta1/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/__init__.py +++ b/tests/unit/gapic/dialogflow_v2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_agents.py b/tests/unit/gapic/dialogflow_v2beta1/test_agents.py index ec733fb0b..3ced64be9 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_agents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_agents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.agents import AgentsAsyncClient from google.cloud.dialogflow_v2beta1.services.agents import AgentsClient from google.cloud.dialogflow_v2beta1.services.agents import pagers from google.cloud.dialogflow_v2beta1.services.agents import transports +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_agents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_agents_client_get_transport_class(): def test_agents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(AgentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_agents_client_client_options_from_dict(): def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -442,41 +471,26 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): api_version=agent.Agent.ApiVersion.API_VERSION_V1, tier=agent.Agent.Tier.TIER_STANDARD, ) - response = client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -488,7 +502,7 @@ def test_get_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -496,7 +510,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -505,7 +518,7 @@ async def test_get_agent_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -531,40 +544,26 @@ async def test_get_agent_async( tier=agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -574,17 +573,17 @@ async def test_get_agent_async_from_dict(): def test_get_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = agent.Agent() - client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -599,17 +598,17 @@ def test_get_agent_field_headers(): @pytest.mark.asyncio async def test_get_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -623,13 +622,12 @@ async def test_get_agent_field_headers_async(): def test_get_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent(parent="parent_value",) @@ -638,12 +636,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_get_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -655,7 +652,7 @@ def test_get_agent_flattened_error(): @pytest.mark.asyncio async def test_get_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: @@ -671,13 +668,12 @@ async def test_get_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_get_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -689,7 +685,7 @@ async def test_get_agent_flattened_error_async(): def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -713,41 +709,26 @@ def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentReque api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) - response = client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -759,7 +740,7 @@ def test_set_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -767,7 +748,6 @@ def test_set_agent_empty_call(): client.set_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() @@ -776,7 +756,7 @@ async def test_set_agent_async( transport: str = "grpc_asyncio", request_type=gcd_agent.SetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,40 +782,26 @@ async def test_set_agent_async( tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - assert response.supported_language_codes == ["supported_language_codes_value"] - assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -845,17 +811,17 @@ async def test_set_agent_async_from_dict(): def test_set_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = gcd_agent.Agent() - client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +838,17 @@ def test_set_agent_field_headers(): @pytest.mark.asyncio async def test_set_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -898,13 +864,12 @@ async def test_set_agent_field_headers_async(): def test_set_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_agent(agent=gcd_agent.Agent(parent="parent_value"),) @@ -913,12 +878,11 @@ def test_set_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") def test_set_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -930,7 +894,7 @@ def test_set_agent_flattened_error(): @pytest.mark.asyncio async def test_set_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: @@ -946,13 +910,12 @@ async def test_set_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") @pytest.mark.asyncio async def test_set_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -964,7 +927,7 @@ async def test_set_agent_flattened_error_async(): def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -975,13 +938,11 @@ def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentReq with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -996,7 +957,7 @@ def test_delete_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1004,7 +965,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1013,7 +973,7 @@ async def test_delete_agent_async( transport: str = "grpc_asyncio", request_type=agent.DeleteAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1024,13 +984,11 @@ async def test_delete_agent_async( with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1043,17 +1001,17 @@ async def test_delete_agent_async_from_dict(): def test_delete_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.DeleteAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = None - client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1068,17 +1026,17 @@ def test_delete_agent_field_headers(): @pytest.mark.asyncio async def test_delete_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.DeleteAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1092,13 +1050,12 @@ async def test_delete_agent_field_headers_async(): def test_delete_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_agent(parent="parent_value",) @@ -1107,12 +1064,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1124,7 +1080,7 @@ def test_delete_agent_flattened_error(): @pytest.mark.asyncio async def test_delete_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: @@ -1140,13 +1096,12 @@ async def test_delete_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1158,7 +1113,7 @@ async def test_delete_agent_flattened_error_async(): def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1171,19 +1126,15 @@ def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsR call.return_value = agent.SearchAgentsResponse( next_page_token="next_page_token_value", ) - response = client.search_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -1195,7 +1146,7 @@ def test_search_agents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1203,7 +1154,6 @@ def test_search_agents_empty_call(): client.search_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() @@ -1212,7 +1162,7 @@ async def test_search_agents_async( transport: str = "grpc_asyncio", request_type=agent.SearchAgentsRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1225,18 +1175,15 @@ async def test_search_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.search_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1246,17 +1193,17 @@ async def test_search_agents_async_from_dict(): def test_search_agents_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: call.return_value = agent.SearchAgentsResponse() - client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1271,11 +1218,12 @@ def test_search_agents_field_headers(): @pytest.mark.asyncio async def test_search_agents_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1231,6 @@ async def test_search_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse() ) - await client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1297,13 +1244,12 @@ async def test_search_agents_field_headers_async(): def test_search_agents_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.SearchAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_agents(parent="parent_value",) @@ -1312,12 +1258,11 @@ def test_search_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_search_agents_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1329,7 +1274,7 @@ def test_search_agents_flattened_error(): @pytest.mark.asyncio async def test_search_agents_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1347,13 +1292,12 @@ async def test_search_agents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_search_agents_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1364,7 +1308,7 @@ async def test_search_agents_flattened_error_async(): def test_search_agents_pager(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1394,7 +1338,7 @@ def test_search_agents_pager(): def test_search_agents_pages(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: @@ -1416,7 +1360,7 @@ def test_search_agents_pages(): @pytest.mark.asyncio async def test_search_agents_async_pager(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1445,7 +1389,7 @@ async def test_search_agents_async_pager(): @pytest.mark.asyncio async def test_search_agents_async_pages(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1471,7 +1415,7 @@ async def test_search_agents_async_pages(): def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1482,13 +1426,11 @@ def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentReque with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1503,7 +1445,7 @@ def test_train_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1511,7 +1453,6 @@ def test_train_agent_empty_call(): client.train_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() @@ -1520,7 +1461,7 @@ async def test_train_agent_async( transport: str = "grpc_asyncio", request_type=agent.TrainAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1533,13 +1474,11 @@ async def test_train_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1552,17 +1491,17 @@ async def test_train_agent_async_from_dict(): def test_train_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1577,11 +1516,12 @@ def test_train_agent_field_headers(): @pytest.mark.asyncio async def test_train_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1529,6 @@ async def test_train_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1603,13 +1542,12 @@ async def test_train_agent_field_headers_async(): def test_train_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.train_agent(parent="parent_value",) @@ -1618,12 +1556,11 @@ def test_train_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_train_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1635,7 +1572,7 @@ def test_train_agent_flattened_error(): @pytest.mark.asyncio async def test_train_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: @@ -1653,13 +1590,12 @@ async def test_train_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_train_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1671,7 +1607,7 @@ async def test_train_agent_flattened_error_async(): def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1682,13 +1618,11 @@ def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentReq with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1703,7 +1637,7 @@ def test_export_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1711,7 +1645,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1720,7 +1653,7 @@ async def test_export_agent_async( transport: str = "grpc_asyncio", request_type=agent.ExportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1733,13 +1666,11 @@ async def test_export_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1752,17 +1683,17 @@ async def test_export_agent_async_from_dict(): def test_export_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ExportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1777,11 +1708,12 @@ def test_export_agent_field_headers(): @pytest.mark.asyncio async def test_export_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ExportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1789,7 +1721,6 @@ async def test_export_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1803,13 +1734,12 @@ async def test_export_agent_field_headers_async(): def test_export_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.export_agent(parent="parent_value",) @@ -1818,12 +1748,11 @@ def test_export_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_export_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1835,7 +1764,7 @@ def test_export_agent_flattened_error(): @pytest.mark.asyncio async def test_export_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: @@ -1853,13 +1782,12 @@ async def test_export_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_export_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1871,7 +1799,7 @@ async def test_export_agent_flattened_error_async(): def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1882,13 +1810,11 @@ def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentReq with mock.patch.object(type(client.transport.import_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1903,7 +1829,7 @@ def test_import_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1911,7 +1837,6 @@ def test_import_agent_empty_call(): client.import_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() @@ -1920,7 +1845,7 @@ async def test_import_agent_async( transport: str = "grpc_asyncio", request_type=agent.ImportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1933,13 +1858,11 @@ async def test_import_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1952,17 +1875,17 @@ async def test_import_agent_async_from_dict(): def test_import_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1977,11 +1900,12 @@ def test_import_agent_field_headers(): @pytest.mark.asyncio async def test_import_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1913,6 @@ async def test_import_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2004,7 +1927,7 @@ async def test_import_agent_field_headers_async(): def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2015,13 +1938,11 @@ def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentR with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -2036,7 +1957,7 @@ def test_restore_agent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1965,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -2053,7 +1973,7 @@ async def test_restore_agent_async( transport: str = "grpc_asyncio", request_type=agent.RestoreAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2066,13 +1986,11 @@ async def test_restore_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -2085,17 +2003,17 @@ async def test_restore_agent_async_from_dict(): def test_restore_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.RestoreAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2110,11 +2028,12 @@ def test_restore_agent_field_headers(): @pytest.mark.asyncio async def test_restore_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.RestoreAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2122,7 +2041,6 @@ async def test_restore_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2139,7 +2057,7 @@ def test_get_validation_result( transport: str = "grpc", request_type=agent.GetValidationResultRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2152,17 +2070,14 @@ def test_get_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = validation_result.ValidationResult() - response = client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) @@ -2174,7 +2089,7 @@ def test_get_validation_result_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2184,7 +2099,6 @@ def test_get_validation_result_empty_call(): client.get_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() @@ -2193,7 +2107,7 @@ async def test_get_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetValidationResultRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2208,13 +2122,11 @@ async def test_get_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - response = await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() # Establish that the response is the type that we expect. @@ -2227,11 +2139,12 @@ async def test_get_validation_result_async_from_dict(): def test_get_validation_result_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2239,7 +2152,6 @@ def test_get_validation_result_field_headers(): type(client.transport.get_validation_result), "__call__" ) as call: call.return_value = validation_result.ValidationResult() - client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2254,11 +2166,12 @@ def test_get_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_validation_result_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = agent.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2268,7 +2181,6 @@ async def test_get_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2284,16 +2196,16 @@ async def test_get_validation_result_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2303,7 +2215,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2314,7 +2226,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AgentsClient(transport=transport) assert client.transport is transport @@ -2323,13 +2235,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AgentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2341,23 +2253,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AgentsGrpcTransport,) def test_agents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2369,7 +2281,7 @@ def test_agents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2395,15 +2307,40 @@ def test_agents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_agents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2419,19 +2356,36 @@ def test_agents_base_transport_with_credentials_file(): def test_agents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_agents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AgentsClient() adc.assert_called_once_with( scopes=( @@ -2442,14 +2396,38 @@ def test_agents_auth_adc(): ) -def test_agents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_agents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AgentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_agents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2459,12 +2437,123 @@ def test_agents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport], ) def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2506,7 +2595,7 @@ def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_agents_host_no_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2516,7 +2605,7 @@ def test_agents_host_no_port(): def test_agents_host_with_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2567,9 +2656,9 @@ def test_agents_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2648,7 +2737,7 @@ def test_agents_transport_channel_mtls_with_adc(transport_class): def test_agents_grpc_lro_client(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2661,7 +2750,7 @@ def test_agents_grpc_lro_client(): def test_agents_grpc_lro_async_client(): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2674,7 +2763,6 @@ def test_agents_grpc_lro_async_client(): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = AgentsClient.agent_path(project) assert expected == actual @@ -2693,7 +2781,6 @@ def test_parse_agent_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2714,7 +2801,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2733,7 +2819,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2752,7 +2837,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2772,7 +2856,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2799,7 +2882,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AgentsTransport, "_prep_wrapped_messages" ) as prep: client = AgentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2808,6 +2891,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AgentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py b/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py index 06408100c..0d8e3982a 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.answer_records import ( AnswerRecordsAsyncClient, @@ -38,12 +37,42 @@ from google.cloud.dialogflow_v2beta1.services.answer_records import AnswerRecordsClient from google.cloud.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.services.answer_records import transports +from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record from google.cloud.dialogflow_v2beta1.types import participant from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_answer_records_client_from_service_account_info(client_class): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -164,7 +193,7 @@ def test_answer_records_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AnswerRecordsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -452,7 +481,7 @@ def test_get_answer_record( transport: str = "grpc", request_type=answer_record.GetAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -470,19 +499,15 @@ def test_get_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, answer_record.AnswerRecord) - assert response.name == "name_value" @@ -494,7 +519,7 @@ def test_get_answer_record_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -504,7 +529,6 @@ def test_get_answer_record_empty_call(): client.get_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() @@ -513,7 +537,7 @@ async def test_get_answer_record_async( transport: str = "grpc_asyncio", request_type=answer_record.GetAnswerRecordRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -528,18 +552,15 @@ async def test_get_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.AnswerRecord(name="name_value",) ) - response = await client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, answer_record.AnswerRecord) - assert response.name == "name_value" @@ -549,11 +570,12 @@ async def test_get_answer_record_async_from_dict(): def test_get_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.GetAnswerRecordRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -561,7 +583,6 @@ def test_get_answer_record_field_headers(): type(client.transport.get_answer_record), "__call__" ) as call: call.return_value = answer_record.AnswerRecord() - client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -576,11 +597,14 @@ def test_get_answer_record_field_headers(): @pytest.mark.asyncio async def test_get_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.GetAnswerRecordRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ async def test_get_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.AnswerRecord() ) - await client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -607,7 +630,7 @@ def test_list_answer_records( transport: str = "grpc", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -622,19 +645,15 @@ def test_list_answer_records( call.return_value = answer_record.ListAnswerRecordsResponse( next_page_token="next_page_token_value", ) - response = client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == "next_page_token_value" @@ -646,7 +665,7 @@ def test_list_answer_records_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -656,7 +675,6 @@ def test_list_answer_records_empty_call(): client.list_answer_records() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() @@ -665,7 +683,7 @@ async def test_list_answer_records_async( transport: str = "grpc_asyncio", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -682,18 +700,15 @@ async def test_list_answer_records_async( next_page_token="next_page_token_value", ) ) - response = await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -703,11 +718,12 @@ async def test_list_answer_records_async_from_dict(): def test_list_answer_records_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -715,7 +731,6 @@ def test_list_answer_records_field_headers(): type(client.transport.list_answer_records), "__call__" ) as call: call.return_value = answer_record.ListAnswerRecordsResponse() - client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -730,11 +745,14 @@ def test_list_answer_records_field_headers(): @pytest.mark.asyncio async def test_list_answer_records_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -744,7 +762,6 @@ async def test_list_answer_records_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.ListAnswerRecordsResponse() ) - await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -758,7 +775,7 @@ async def test_list_answer_records_field_headers_async(): def test_list_answer_records_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -766,7 +783,6 @@ def test_list_answer_records_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = answer_record.ListAnswerRecordsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_answer_records(parent="parent_value",) @@ -775,12 +791,11 @@ def test_list_answer_records_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -792,7 +807,9 @@ def test_list_answer_records_flattened_error(): @pytest.mark.asyncio async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -812,13 +829,14 @@ async def test_list_answer_records_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -829,7 +847,7 @@ async def test_list_answer_records_flattened_error_async(): def test_list_answer_records_pager(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -874,7 +892,7 @@ def test_list_answer_records_pager(): def test_list_answer_records_pages(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -911,7 +929,7 @@ def test_list_answer_records_pages(): @pytest.mark.asyncio async def test_list_answer_records_async_pager(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -955,7 +973,7 @@ async def test_list_answer_records_async_pager(): @pytest.mark.asyncio async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -998,7 +1016,7 @@ def test_update_answer_record( transport: str = "grpc", request_type=gcd_answer_record.UpdateAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1016,19 +1034,15 @@ def test_update_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -1040,7 +1054,7 @@ def test_update_answer_record_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1050,7 +1064,6 @@ def test_update_answer_record_empty_call(): client.update_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() @@ -1060,7 +1073,7 @@ async def test_update_answer_record_async( request_type=gcd_answer_record.UpdateAnswerRecordRequest, ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1075,18 +1088,15 @@ async def test_update_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord(name="name_value",) ) - response = await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -1096,11 +1106,12 @@ async def test_update_answer_record_async_from_dict(): def test_update_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1108,7 +1119,6 @@ def test_update_answer_record_field_headers(): type(client.transport.update_answer_record), "__call__" ) as call: call.return_value = gcd_answer_record.AnswerRecord() - client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1126,11 +1136,14 @@ def test_update_answer_record_field_headers(): @pytest.mark.asyncio async def test_update_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1140,7 +1153,6 @@ async def test_update_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord() ) - await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1157,7 +1169,7 @@ async def test_update_answer_record_field_headers_async(): def test_update_answer_record_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1165,28 +1177,25 @@ def test_update_answer_record_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_answer_record.AnswerRecord() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].answer_record == gcd_answer_record.AnswerRecord( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_answer_record_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1194,13 +1203,15 @@ def test_update_answer_record_flattened_error(): client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1216,24 +1227,24 @@ async def test_update_answer_record_flattened_async(): # using the keyword arguments to the method. response = await client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].answer_record == gcd_answer_record.AnswerRecord( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1241,23 +1252,23 @@ async def test_update_answer_record_flattened_error_async(): await client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1267,7 +1278,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1278,7 +1289,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AnswerRecordsClient(transport=transport) assert client.transport is transport @@ -1287,13 +1298,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1308,23 +1319,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AnswerRecordsGrpcTransport,) def test_answer_records_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1336,7 +1347,7 @@ def test_answer_records_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1351,15 +1362,40 @@ def test_answer_records_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_answer_records_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1375,19 +1411,36 @@ def test_answer_records_base_transport_with_credentials_file(): def test_answer_records_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_answer_records_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_answer_records_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AnswerRecordsClient() adc.assert_called_once_with( scopes=( @@ -1398,14 +1451,44 @@ def test_answer_records_auth_adc(): ) -def test_answer_records_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AnswerRecordsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1415,6 +1498,121 @@ def test_answer_records_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1423,7 +1621,7 @@ def test_answer_records_transport_auth_adc(): ], ) def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1465,7 +1663,7 @@ def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_cla def test_answer_records_host_no_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1475,7 +1673,7 @@ def test_answer_records_host_no_port(): def test_answer_records_host_with_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1529,9 +1727,9 @@ def test_answer_records_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1614,7 +1812,6 @@ def test_answer_records_transport_channel_mtls_with_adc(transport_class): def test_answer_record_path(): project = "squid" answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format( project=project, answer_record=answer_record, ) @@ -1636,7 +1833,6 @@ def test_parse_answer_record_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1657,7 +1853,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AnswerRecordsClient.common_folder_path(folder) assert expected == actual @@ -1676,7 +1871,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AnswerRecordsClient.common_organization_path(organization) assert expected == actual @@ -1695,7 +1889,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AnswerRecordsClient.common_project_path(project) assert expected == actual @@ -1715,7 +1908,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1742,7 +1934,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AnswerRecordsTransport, "_prep_wrapped_messages" ) as prep: client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1751,6 +1943,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AnswerRecordsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py b/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py index dcdec7af4..d89080a5c 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.contexts import ContextsAsyncClient from google.cloud.dialogflow_v2beta1.services.contexts import ContextsClient from google.cloud.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.services.contexts import transports +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_contexts_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_contexts_client_get_transport_class(): def test_contexts_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(ContextsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -420,7 +449,7 @@ def test_list_contexts( transport: str = "grpc", request_type=context.ListContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -433,19 +462,15 @@ def test_list_contexts( call.return_value = context.ListContextsResponse( next_page_token="next_page_token_value", ) - response = client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_contexts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -465,7 +490,6 @@ def test_list_contexts_empty_call(): client.list_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() @@ -474,7 +498,7 @@ async def test_list_contexts_async( transport: str = "grpc_asyncio", request_type=context.ListContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -487,18 +511,15 @@ async def test_list_contexts_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContextsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_contexts_async_from_dict(): def test_list_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: call.return_value = context.ListContextsResponse() - client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_contexts_field_headers(): @pytest.mark.asyncio async def test_list_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_contexts_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse() ) - await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_contexts_field_headers_async(): def test_list_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.ListContextsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_contexts(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -591,7 +610,7 @@ def test_list_contexts_flattened_error(): @pytest.mark.asyncio async def test_list_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_contexts_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -626,7 +644,7 @@ async def test_list_contexts_flattened_error_async(): def test_list_contexts_pager(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_contexts_pager(): def test_list_contexts_pages(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_contexts_pages(): @pytest.mark.asyncio async def test_list_contexts_async_pager(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +737,7 @@ async def test_list_contexts_async_pager(): @pytest.mark.asyncio async def test_list_contexts_async_pages(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -749,7 +767,7 @@ async def test_list_contexts_async_pages(): def test_get_context(transport: str = "grpc", request_type=context.GetContextRequest): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -760,21 +778,16 @@ def test_get_context(transport: str = "grpc", request_type=context.GetContextReq with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context(name="name_value", lifespan_count=1498,) - response = client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -786,7 +799,7 @@ def test_get_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -794,7 +807,6 @@ def test_get_context_empty_call(): client.get_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() @@ -803,7 +815,7 @@ async def test_get_context_async( transport: str = "grpc_asyncio", request_type=context.GetContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -816,20 +828,16 @@ async def test_get_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -839,17 +847,17 @@ async def test_get_context_async_from_dict(): def test_get_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = context.Context() - client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -864,17 +872,17 @@ def test_get_context_field_headers(): @pytest.mark.asyncio async def test_get_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - await client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -888,13 +896,12 @@ async def test_get_context_field_headers_async(): def test_get_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_context(name="name_value",) @@ -903,12 +910,11 @@ def test_get_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +926,7 @@ def test_get_context_flattened_error(): @pytest.mark.asyncio async def test_get_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: @@ -936,13 +942,12 @@ async def test_get_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +961,7 @@ def test_create_context( transport: str = "grpc", request_type=gcd_context.CreateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,21 +972,16 @@ def test_create_context( with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -993,7 +993,7 @@ def test_create_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +1001,6 @@ def test_create_context_empty_call(): client.create_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() @@ -1010,7 +1009,7 @@ async def test_create_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.CreateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1023,20 +1022,16 @@ async def test_create_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1046,17 +1041,17 @@ async def test_create_context_async_from_dict(): def test_create_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = gcd_context.Context() - client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1071,17 +1066,17 @@ def test_create_context_field_headers(): @pytest.mark.asyncio async def test_create_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1095,13 +1090,12 @@ async def test_create_context_field_headers_async(): def test_create_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_context( @@ -1112,14 +1106,12 @@ def test_create_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") def test_create_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1133,7 +1125,7 @@ def test_create_context_flattened_error(): @pytest.mark.asyncio async def test_create_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: @@ -1151,15 +1143,13 @@ async def test_create_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") @pytest.mark.asyncio async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,7 +1165,7 @@ def test_update_context( transport: str = "grpc", request_type=gcd_context.UpdateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1186,21 +1176,16 @@ def test_update_context( with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1212,7 +1197,7 @@ def test_update_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1205,6 @@ def test_update_context_empty_call(): client.update_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() @@ -1229,7 +1213,7 @@ async def test_update_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.UpdateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,20 +1226,16 @@ async def test_update_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1265,17 +1245,17 @@ async def test_update_context_async_from_dict(): def test_update_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = gcd_context.Context() - client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1292,17 +1272,17 @@ def test_update_context_field_headers(): @pytest.mark.asyncio async def test_update_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1318,32 +1298,29 @@ async def test_update_context_field_headers_async(): def test_update_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_context( context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].context == gcd_context.Context(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1351,13 +1328,13 @@ def test_update_context_flattened_error(): client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: @@ -1369,22 +1346,20 @@ async def test_update_context_flattened_async(): # using the keyword arguments to the method. response = await client.update_context( context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].context == gcd_context.Context(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1392,7 +1367,7 @@ async def test_update_context_flattened_error_async(): await client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1400,7 +1375,7 @@ def test_delete_context( transport: str = "grpc", request_type=context.DeleteContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1411,13 +1386,11 @@ def test_delete_context( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1432,7 +1405,7 @@ def test_delete_context_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1440,7 +1413,6 @@ def test_delete_context_empty_call(): client.delete_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() @@ -1449,7 +1421,7 @@ async def test_delete_context_async( transport: str = "grpc_asyncio", request_type=context.DeleteContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1460,13 +1432,11 @@ async def test_delete_context_async( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1479,17 +1449,17 @@ async def test_delete_context_async_from_dict(): def test_delete_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = None - client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1504,17 +1474,17 @@ def test_delete_context_field_headers(): @pytest.mark.asyncio async def test_delete_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1528,13 +1498,12 @@ async def test_delete_context_field_headers_async(): def test_delete_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_context(name="name_value",) @@ -1543,12 +1512,11 @@ def test_delete_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1560,7 +1528,7 @@ def test_delete_context_flattened_error(): @pytest.mark.asyncio async def test_delete_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: @@ -1576,13 +1544,12 @@ async def test_delete_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,7 +1563,7 @@ def test_delete_all_contexts( transport: str = "grpc", request_type=context.DeleteAllContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1609,13 +1576,11 @@ def test_delete_all_contexts( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1630,7 +1595,7 @@ def test_delete_all_contexts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1640,7 +1605,6 @@ def test_delete_all_contexts_empty_call(): client.delete_all_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() @@ -1649,7 +1613,7 @@ async def test_delete_all_contexts_async( transport: str = "grpc_asyncio", request_type=context.DeleteAllContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1626,11 @@ async def test_delete_all_contexts_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1681,11 +1643,12 @@ async def test_delete_all_contexts_async_from_dict(): def test_delete_all_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1656,6 @@ def test_delete_all_contexts_field_headers(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = None - client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1670,12 @@ def test_delete_all_contexts_field_headers(): @pytest.mark.asyncio async def test_delete_all_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1683,6 @@ async def test_delete_all_contexts_field_headers_async(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1734,7 +1696,7 @@ async def test_delete_all_contexts_field_headers_async(): def test_delete_all_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1742,7 +1704,6 @@ def test_delete_all_contexts_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_all_contexts(parent="parent_value",) @@ -1751,12 +1712,11 @@ def test_delete_all_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_all_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1768,7 +1728,7 @@ def test_delete_all_contexts_flattened_error(): @pytest.mark.asyncio async def test_delete_all_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1786,13 +1746,12 @@ async def test_delete_all_contexts_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1805,16 +1764,16 @@ async def test_delete_all_contexts_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1824,7 +1783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1835,7 +1794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ContextsClient(transport=transport) assert client.transport is transport @@ -1844,13 +1803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ContextsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1862,23 +1821,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ContextsGrpcTransport,) def test_contexts_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1890,7 +1849,7 @@ def test_contexts_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1908,15 +1867,40 @@ def test_contexts_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_contexts_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1932,19 +1916,36 @@ def test_contexts_base_transport_with_credentials_file(): def test_contexts_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_contexts_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_contexts_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ContextsClient() adc.assert_called_once_with( scopes=( @@ -1955,14 +1956,38 @@ def test_contexts_auth_adc(): ) -def test_contexts_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ContextsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1972,12 +1997,123 @@ def test_contexts_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport], ) def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2019,7 +2155,7 @@ def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): def test_contexts_host_no_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2029,7 +2165,7 @@ def test_contexts_host_no_port(): def test_contexts_host_with_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2080,9 +2216,9 @@ def test_contexts_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2163,7 +2299,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2186,7 +2321,6 @@ def test_parse_context_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2207,7 +2341,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = ContextsClient.common_folder_path(folder) assert expected == actual @@ -2226,7 +2359,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = ContextsClient.common_organization_path(organization) assert expected == actual @@ -2245,7 +2377,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = ContextsClient.common_project_path(project) assert expected == actual @@ -2265,7 +2396,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2292,7 +2422,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ContextsTransport, "_prep_wrapped_messages" ) as prep: client = ContextsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2301,6 +2431,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ContextsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py b/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py index 8aa9c1358..d37a99401 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.conversation_profiles import ( ConversationProfilesAsyncClient, @@ -40,6 +39,12 @@ ) from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers from google.cloud.dialogflow_v2beta1.services.conversation_profiles import transports +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import conversation_profile from google.cloud.dialogflow_v2beta1.types import ( @@ -47,8 +52,32 @@ ) from google.cloud.dialogflow_v2beta1.types import participant from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -117,7 +146,7 @@ def test_conversation_profiles_client_from_service_account_info(client_class): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -174,7 +203,7 @@ def test_conversation_profiles_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationProfilesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -481,7 +510,7 @@ def test_list_conversation_profiles( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -496,19 +525,15 @@ def test_list_conversation_profiles( call.return_value = conversation_profile.ListConversationProfilesResponse( next_page_token="next_page_token_value", ) - response = client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == "next_page_token_value" @@ -520,7 +545,7 @@ def test_list_conversation_profiles_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -530,7 +555,6 @@ def test_list_conversation_profiles_empty_call(): client.list_conversation_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() @@ -540,7 +564,7 @@ async def test_list_conversation_profiles_async( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -557,18 +581,15 @@ async def test_list_conversation_profiles_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationProfilesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -578,11 +599,14 @@ async def test_list_conversation_profiles_async_from_dict(): def test_list_conversation_profiles_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ def test_list_conversation_profiles_field_headers(): type(client.transport.list_conversation_profiles), "__call__" ) as call: call.return_value = conversation_profile.ListConversationProfilesResponse() - client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -606,12 +629,13 @@ def test_list_conversation_profiles_field_headers(): @pytest.mark.asyncio async def test_list_conversation_profiles_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -621,7 +645,6 @@ async def test_list_conversation_profiles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ListConversationProfilesResponse() ) - await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -635,7 +658,9 @@ async def test_list_conversation_profiles_field_headers_async(): def test_list_conversation_profiles_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -643,7 +668,6 @@ def test_list_conversation_profiles_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ListConversationProfilesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversation_profiles(parent="parent_value",) @@ -652,12 +676,13 @@ def test_list_conversation_profiles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -671,7 +696,7 @@ def test_list_conversation_profiles_flattened_error(): @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -692,14 +717,13 @@ async def test_list_conversation_profiles_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -712,7 +736,9 @@ async def test_list_conversation_profiles_flattened_error_async(): def test_list_conversation_profiles_pager(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -760,7 +786,9 @@ def test_list_conversation_profiles_pager(): def test_list_conversation_profiles_pages(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -799,7 +827,7 @@ def test_list_conversation_profiles_pages(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pager(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -848,7 +876,7 @@ async def test_list_conversation_profiles_async_pager(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pages(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -894,7 +922,7 @@ def test_get_conversation_profile( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -911,23 +939,17 @@ def test_get_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -939,7 +961,7 @@ def test_get_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -949,7 +971,6 @@ def test_get_conversation_profile_empty_call(): client.get_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() @@ -959,7 +980,7 @@ async def test_get_conversation_profile_async( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -978,22 +999,17 @@ async def test_get_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1003,11 +1019,14 @@ async def test_get_conversation_profile_async_from_dict(): def test_get_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1015,7 +1034,6 @@ def test_get_conversation_profile_field_headers(): type(client.transport.get_conversation_profile), "__call__" ) as call: call.return_value = conversation_profile.ConversationProfile() - client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1031,12 +1049,13 @@ def test_get_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_get_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1046,7 +1065,6 @@ async def test_get_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ConversationProfile() ) - await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1060,7 +1078,9 @@ async def test_get_conversation_profile_field_headers_async(): def test_get_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1068,7 +1088,6 @@ def test_get_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation_profile(name="name_value",) @@ -1077,12 +1096,13 @@ def test_get_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1095,7 +1115,7 @@ def test_get_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1116,14 +1136,13 @@ async def test_get_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1139,7 +1158,7 @@ def test_create_conversation_profile( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1156,23 +1175,17 @@ def test_create_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1184,7 +1197,7 @@ def test_create_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1194,7 +1207,6 @@ def test_create_conversation_profile_empty_call(): client.create_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() @@ -1204,7 +1216,7 @@ async def test_create_conversation_profile_async( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1223,22 +1235,17 @@ async def test_create_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1248,11 +1255,14 @@ async def test_create_conversation_profile_async_from_dict(): def test_create_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1260,7 +1270,6 @@ def test_create_conversation_profile_field_headers(): type(client.transport.create_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1276,12 +1285,13 @@ def test_create_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_create_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1291,7 +1301,6 @@ async def test_create_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1305,7 +1314,9 @@ async def test_create_conversation_profile_field_headers_async(): def test_create_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,7 +1324,6 @@ def test_create_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation_profile( @@ -1327,9 +1337,7 @@ def test_create_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1338,7 +1346,9 @@ def test_create_conversation_profile_flattened(): def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1355,7 +1365,7 @@ def test_create_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1381,9 +1391,7 @@ async def test_create_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1394,7 +1402,7 @@ async def test_create_conversation_profile_flattened_async(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1414,7 +1422,7 @@ def test_update_conversation_profile( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1431,23 +1439,17 @@ def test_update_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1459,7 +1461,7 @@ def test_update_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1469,7 +1471,6 @@ def test_update_conversation_profile_empty_call(): client.update_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() @@ -1479,7 +1480,7 @@ async def test_update_conversation_profile_async( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1498,22 +1499,17 @@ async def test_update_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1523,11 +1519,14 @@ async def test_update_conversation_profile_async_from_dict(): def test_update_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1535,7 +1534,6 @@ def test_update_conversation_profile_field_headers(): type(client.transport.update_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1554,12 +1552,13 @@ def test_update_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_update_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1569,7 +1568,6 @@ async def test_update_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1586,7 +1584,9 @@ async def test_update_conversation_profile_field_headers_async(): def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1594,32 +1594,31 @@ def test_update_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_conversation_profile( conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1629,14 +1628,14 @@ def test_update_conversation_profile_flattened_error(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1655,27 +1654,25 @@ async def test_update_conversation_profile_flattened_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1686,7 +1683,7 @@ async def test_update_conversation_profile_flattened_error_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1695,7 +1692,7 @@ def test_delete_conversation_profile( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1708,13 +1705,11 @@ def test_delete_conversation_profile( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1729,7 +1724,7 @@ def test_delete_conversation_profile_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1739,7 +1734,6 @@ def test_delete_conversation_profile_empty_call(): client.delete_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() @@ -1749,7 +1743,7 @@ async def test_delete_conversation_profile_async( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1762,13 +1756,11 @@ async def test_delete_conversation_profile_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1781,11 +1773,14 @@ async def test_delete_conversation_profile_async_from_dict(): def test_delete_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1793,7 +1788,6 @@ def test_delete_conversation_profile_field_headers(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = None - client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1809,12 +1803,13 @@ def test_delete_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_delete_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1822,7 +1817,6 @@ async def test_delete_conversation_profile_field_headers_async(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1836,7 +1830,9 @@ async def test_delete_conversation_profile_field_headers_async(): def test_delete_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1844,7 +1840,6 @@ def test_delete_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_conversation_profile(name="name_value",) @@ -1853,12 +1848,13 @@ def test_delete_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1871,7 +1867,7 @@ def test_delete_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1890,14 +1886,13 @@ async def test_delete_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1911,16 +1906,16 @@ async def test_delete_conversation_profile_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1930,7 +1925,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1941,7 +1936,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationProfilesClient(transport=transport) assert client.transport is transport @@ -1950,13 +1945,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1971,23 +1966,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.ConversationProfilesGrpcTransport,) def test_conversation_profiles_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1999,7 +1996,7 @@ def test_conversation_profiles_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2016,15 +2013,40 @@ def test_conversation_profiles_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2040,19 +2062,36 @@ def test_conversation_profiles_base_transport_with_credentials_file(): def test_conversation_profiles_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ConversationProfilesClient() adc.assert_called_once_with( scopes=( @@ -2063,14 +2102,44 @@ def test_conversation_profiles_auth_adc(): ) -def test_conversation_profiles_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ConversationProfilesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2080,6 +2149,121 @@ def test_conversation_profiles_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2090,7 +2274,7 @@ def test_conversation_profiles_transport_auth_adc(): def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2132,7 +2316,7 @@ def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( def test_conversation_profiles_host_no_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2142,7 +2326,7 @@ def test_conversation_profiles_host_no_port(): def test_conversation_profiles_host_with_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2198,9 +2382,9 @@ def test_conversation_profiles_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2282,7 +2466,6 @@ def test_conversation_profiles_transport_channel_mtls_with_adc(transport_class): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = ConversationProfilesClient.agent_path(project) assert expected == actual @@ -2299,10 +2482,35 @@ def test_parse_agent_path(): assert expected == actual -def test_conversation_profile_path(): +def test_conversation_model_path(): project = "whelk" - conversation_profile = "octopus" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + actual = ConversationProfilesClient.conversation_model_path( + project, location, conversation_model + ) + assert expected == actual + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2314,8 +2522,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "oyster", - "conversation_profile": "nudibranch", + "project": "scallop", + "conversation_profile": "abalone", } path = ConversationProfilesClient.conversation_profile_path(**expected) @@ -2325,10 +2533,9 @@ def test_parse_conversation_profile_path(): def test_document_path(): - project = "cuttlefish" - knowledge_base = "mussel" - document = "winkle" - + project = "squid" + knowledge_base = "clam" + document = "whelk" expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2338,9 +2545,9 @@ def test_document_path(): def test_parse_document_path(): expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", } path = ConversationProfilesClient.document_path(**expected) @@ -2350,9 +2557,8 @@ def test_parse_document_path(): def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - + project = "cuttlefish" + knowledge_base = "mussel" expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2362,8 +2568,8 @@ def test_knowledge_base_path(): def test_parse_knowledge_base_path(): expected = { - "project": "whelk", - "knowledge_base": "octopus", + "project": "winkle", + "knowledge_base": "nautilus", } path = ConversationProfilesClient.knowledge_base_path(**expected) @@ -2373,8 +2579,7 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): - billing_account = "oyster" - + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2384,7 +2589,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = ConversationProfilesClient.common_billing_account_path(**expected) @@ -2394,8 +2599,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "squid" expected = "folders/{folder}".format(folder=folder,) actual = ConversationProfilesClient.common_folder_path(folder) assert expected == actual @@ -2403,7 +2607,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = ConversationProfilesClient.common_folder_path(**expected) @@ -2413,8 +2617,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "whelk" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationProfilesClient.common_organization_path(organization) assert expected == actual @@ -2422,7 +2625,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = ConversationProfilesClient.common_organization_path(**expected) @@ -2432,8 +2635,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "oyster" expected = "projects/{project}".format(project=project,) actual = ConversationProfilesClient.common_project_path(project) assert expected == actual @@ -2441,7 +2643,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = ConversationProfilesClient.common_project_path(**expected) @@ -2451,9 +2653,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2463,8 +2664,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = ConversationProfilesClient.common_location_path(**expected) @@ -2480,7 +2681,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationProfilesTransport, "_prep_wrapped_messages" ) as prep: client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2489,6 +2690,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationProfilesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py index daa1b4d91..15d4d7f0c 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.conversations import ( ConversationsAsyncClient, @@ -38,13 +37,43 @@ from google.cloud.dialogflow_v2beta1.services.conversations import ConversationsClient from google.cloud.dialogflow_v2beta1.services.conversations import pagers from google.cloud.dialogflow_v2beta1.services.conversations import transports +from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import session from google.oauth2 import service_account -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -95,7 +124,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -112,7 +141,7 @@ def test_conversations_client_from_service_account_info(client_class): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -165,7 +194,7 @@ def test_conversations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -453,7 +482,7 @@ def test_create_conversation( transport: str = "grpc", request_type=gcd_conversation.CreateConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -471,28 +500,21 @@ def test_create_conversation( conversation_profile="conversation_profile_value", conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -507,7 +529,7 @@ def test_create_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -517,7 +539,6 @@ def test_create_conversation_empty_call(): client.create_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() @@ -527,7 +548,7 @@ async def test_create_conversation_async( request_type=gcd_conversation.CreateConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -547,27 +568,21 @@ async def test_create_conversation_async( conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -580,11 +595,12 @@ async def test_create_conversation_async_from_dict(): def test_create_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -592,7 +608,6 @@ def test_create_conversation_field_headers(): type(client.transport.create_conversation), "__call__" ) as call: call.return_value = gcd_conversation.Conversation() - client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -607,11 +622,14 @@ def test_create_conversation_field_headers(): @pytest.mark.asyncio async def test_create_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -621,7 +639,6 @@ async def test_create_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation.Conversation() ) - await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -635,7 +652,7 @@ async def test_create_conversation_field_headers_async(): def test_create_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -643,7 +660,6 @@ def test_create_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation( @@ -655,14 +671,12 @@ def test_create_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") def test_create_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -676,7 +690,9 @@ def test_create_conversation_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,15 +715,15 @@ async def test_create_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") @pytest.mark.asyncio async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -723,7 +739,7 @@ def test_list_conversations( transport: str = "grpc", request_type=conversation.ListConversationsRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -738,19 +754,15 @@ def test_list_conversations( call.return_value = conversation.ListConversationsResponse( next_page_token="next_page_token_value", ) - response = client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == "next_page_token_value" @@ -762,7 +774,7 @@ def test_list_conversations_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -772,7 +784,6 @@ def test_list_conversations_empty_call(): client.list_conversations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() @@ -781,7 +792,7 @@ async def test_list_conversations_async( transport: str = "grpc_asyncio", request_type=conversation.ListConversationsRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -798,18 +809,15 @@ async def test_list_conversations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -819,11 +827,12 @@ async def test_list_conversations_async_from_dict(): def test_list_conversations_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -831,7 +840,6 @@ def test_list_conversations_field_headers(): type(client.transport.list_conversations), "__call__" ) as call: call.return_value = conversation.ListConversationsResponse() - client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -846,11 +854,14 @@ def test_list_conversations_field_headers(): @pytest.mark.asyncio async def test_list_conversations_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -860,7 +871,6 @@ async def test_list_conversations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListConversationsResponse() ) - await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -874,7 +884,7 @@ async def test_list_conversations_field_headers_async(): def test_list_conversations_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -882,7 +892,6 @@ def test_list_conversations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversations(parent="parent_value",) @@ -891,12 +900,11 @@ def test_list_conversations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversations_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -908,7 +916,9 @@ def test_list_conversations_flattened_error(): @pytest.mark.asyncio async def test_list_conversations_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -928,13 +938,14 @@ async def test_list_conversations_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_conversations_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -945,7 +956,7 @@ async def test_list_conversations_flattened_error_async(): def test_list_conversations_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -990,7 +1001,7 @@ def test_list_conversations_pager(): def test_list_conversations_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1027,7 +1038,7 @@ def test_list_conversations_pages(): @pytest.mark.asyncio async def test_list_conversations_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1071,7 +1082,7 @@ async def test_list_conversations_async_pager(): @pytest.mark.asyncio async def test_list_conversations_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1114,7 +1125,7 @@ def test_get_conversation( transport: str = "grpc", request_type=conversation.GetConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1130,27 +1141,20 @@ def test_get_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1165,7 +1169,7 @@ def test_get_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1173,7 +1177,6 @@ def test_get_conversation_empty_call(): client.get_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() @@ -1182,7 +1185,7 @@ async def test_get_conversation_async( transport: str = "grpc_asyncio", request_type=conversation.GetConversationRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1200,26 +1203,20 @@ async def test_get_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1232,17 +1229,17 @@ async def test_get_conversation_async_from_dict(): def test_get_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: call.return_value = conversation.Conversation() - client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1257,11 +1254,14 @@ def test_get_conversation_field_headers(): @pytest.mark.asyncio async def test_get_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1269,7 +1269,6 @@ async def test_get_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1283,13 +1282,12 @@ async def test_get_conversation_field_headers_async(): def test_get_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation(name="name_value",) @@ -1298,12 +1296,11 @@ def test_get_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1315,7 +1312,9 @@ def test_get_conversation_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: @@ -1333,13 +1332,14 @@ async def test_get_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1353,7 +1353,7 @@ def test_complete_conversation( transport: str = "grpc", request_type=conversation.CompleteConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1371,27 +1371,20 @@ def test_complete_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1406,7 +1399,7 @@ def test_complete_conversation_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1416,7 +1409,6 @@ def test_complete_conversation_empty_call(): client.complete_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() @@ -1426,7 +1418,7 @@ async def test_complete_conversation_async( request_type=conversation.CompleteConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1446,26 +1438,20 @@ async def test_complete_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1478,11 +1464,12 @@ async def test_complete_conversation_async_from_dict(): def test_complete_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1490,7 +1477,6 @@ def test_complete_conversation_field_headers(): type(client.transport.complete_conversation), "__call__" ) as call: call.return_value = conversation.Conversation() - client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1505,11 +1491,14 @@ def test_complete_conversation_field_headers(): @pytest.mark.asyncio async def test_complete_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1519,7 +1508,6 @@ async def test_complete_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1533,7 +1521,7 @@ async def test_complete_conversation_field_headers_async(): def test_complete_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1541,7 +1529,6 @@ def test_complete_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.complete_conversation(name="name_value",) @@ -1550,12 +1537,11 @@ def test_complete_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_complete_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1567,7 +1553,9 @@ def test_complete_conversation_flattened_error(): @pytest.mark.asyncio async def test_complete_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1587,13 +1575,14 @@ async def test_complete_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1607,7 +1596,7 @@ def test_batch_create_messages( transport: str = "grpc", request_type=conversation.BatchCreateMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1620,17 +1609,14 @@ def test_batch_create_messages( ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.BatchCreateMessagesResponse() - response = client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.BatchCreateMessagesResponse) @@ -1642,7 +1628,7 @@ def test_batch_create_messages_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1652,7 +1638,6 @@ def test_batch_create_messages_empty_call(): client.batch_create_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() @@ -1662,7 +1647,7 @@ async def test_batch_create_messages_async( request_type=conversation.BatchCreateMessagesRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1677,13 +1662,11 @@ async def test_batch_create_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.BatchCreateMessagesResponse() ) - response = await client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() # Establish that the response is the type that we expect. @@ -1696,11 +1679,12 @@ async def test_batch_create_messages_async_from_dict(): def test_batch_create_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.BatchCreateMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1708,7 +1692,6 @@ def test_batch_create_messages_field_headers(): type(client.transport.batch_create_messages), "__call__" ) as call: call.return_value = conversation.BatchCreateMessagesResponse() - client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1723,11 +1706,14 @@ def test_batch_create_messages_field_headers(): @pytest.mark.asyncio async def test_batch_create_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.BatchCreateMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1737,7 +1723,6 @@ async def test_batch_create_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.BatchCreateMessagesResponse() ) - await client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1751,7 +1736,7 @@ async def test_batch_create_messages_field_headers_async(): def test_batch_create_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1759,7 +1744,6 @@ def test_batch_create_messages_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.BatchCreateMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_create_messages(parent="parent_value",) @@ -1768,12 +1752,11 @@ def test_batch_create_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_batch_create_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1785,7 +1768,9 @@ def test_batch_create_messages_flattened_error(): @pytest.mark.asyncio async def test_batch_create_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1805,13 +1790,14 @@ async def test_batch_create_messages_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_batch_create_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1825,7 +1811,7 @@ def test_list_messages( transport: str = "grpc", request_type=conversation.ListMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1838,19 +1824,15 @@ def test_list_messages( call.return_value = conversation.ListMessagesResponse( next_page_token="next_page_token_value", ) - response = client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == "next_page_token_value" @@ -1862,7 +1844,7 @@ def test_list_messages_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1870,7 +1852,6 @@ def test_list_messages_empty_call(): client.list_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() @@ -1879,7 +1860,7 @@ async def test_list_messages_async( transport: str = "grpc_asyncio", request_type=conversation.ListMessagesRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1892,18 +1873,15 @@ async def test_list_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMessagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1913,17 +1891,17 @@ async def test_list_messages_async_from_dict(): def test_list_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: call.return_value = conversation.ListMessagesResponse() - client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1938,11 +1916,14 @@ def test_list_messages_field_headers(): @pytest.mark.asyncio async def test_list_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1950,7 +1931,6 @@ async def test_list_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse() ) - await client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1964,13 +1944,12 @@ async def test_list_messages_field_headers_async(): def test_list_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_messages(parent="parent_value",) @@ -1979,12 +1958,11 @@ def test_list_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1996,7 +1974,9 @@ def test_list_messages_flattened_error(): @pytest.mark.asyncio async def test_list_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2014,13 +1994,14 @@ async def test_list_messages_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2031,7 +2012,7 @@ async def test_list_messages_flattened_error_async(): def test_list_messages_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2069,7 +2050,7 @@ def test_list_messages_pager(): def test_list_messages_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2099,7 +2080,7 @@ def test_list_messages_pages(): @pytest.mark.asyncio async def test_list_messages_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2136,7 +2117,7 @@ async def test_list_messages_async_pager(): @pytest.mark.asyncio async def test_list_messages_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2171,16 +2152,16 @@ async def test_list_messages_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -2190,7 +2171,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -2201,7 +2182,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationsClient(transport=transport) assert client.transport is transport @@ -2210,13 +2191,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2231,23 +2212,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ConversationsGrpcTransport,) def test_conversations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2259,7 +2240,7 @@ def test_conversations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2277,15 +2258,40 @@ def test_conversations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2301,19 +2307,36 @@ def test_conversations_base_transport_with_credentials_file(): def test_conversations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_conversations_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ConversationsClient() adc.assert_called_once_with( scopes=( @@ -2324,14 +2347,44 @@ def test_conversations_auth_adc(): ) -def test_conversations_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ConversationsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2341,6 +2394,121 @@ def test_conversations_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2349,7 +2517,7 @@ def test_conversations_transport_auth_adc(): ], ) def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2391,7 +2559,7 @@ def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_clas def test_conversations_host_no_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2401,7 +2569,7 @@ def test_conversations_host_no_port(): def test_conversations_host_with_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2455,9 +2623,9 @@ def test_conversations_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2540,7 +2708,6 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): def test_conversation_path(): project = "squid" conversation = "clam" - expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, ) @@ -2563,7 +2730,6 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): project = "oyster" conversation_profile = "nudibranch" - expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2589,7 +2755,6 @@ def test_message_path(): project = "winkle" conversation = "nautilus" message = "scallop" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2612,7 +2777,6 @@ def test_parse_message_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2633,7 +2797,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) assert expected == actual @@ -2652,7 +2815,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) assert expected == actual @@ -2671,7 +2833,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) assert expected == actual @@ -2691,7 +2852,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2718,7 +2878,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationsTransport, "_prep_wrapped_messages" ) as prep: client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2727,6 +2887,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_documents.py b/tests/unit/gapic/dialogflow_v2beta1/test_documents.py index 0ecfd8a80..32100084a 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_documents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_documents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,30 +23,60 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.documents import DocumentsAsyncClient from google.cloud.dialogflow_v2beta1.services.documents import DocumentsClient from google.cloud.dialogflow_v2beta1.services.documents import pagers from google.cloud.dialogflow_v2beta1.services.documents import transports +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -106,7 +135,7 @@ def test_documents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -155,7 +184,7 @@ def test_documents_client_get_transport_class(): def test_documents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(DocumentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -439,7 +468,7 @@ def test_list_documents( transport: str = "grpc", request_type=document.ListDocumentsRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -452,19 +481,15 @@ def test_list_documents( call.return_value = document.ListDocumentsResponse( next_page_token="next_page_token_value", ) - response = client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == "next_page_token_value" @@ -476,7 +501,7 @@ def test_list_documents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -484,7 +509,6 @@ def test_list_documents_empty_call(): client.list_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() @@ -493,7 +517,7 @@ async def test_list_documents_async( transport: str = "grpc_asyncio", request_type=document.ListDocumentsRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -506,18 +530,15 @@ async def test_list_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -527,17 +548,17 @@ async def test_list_documents_async_from_dict(): def test_list_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: call.return_value = document.ListDocumentsResponse() - client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -552,11 +573,12 @@ def test_list_documents_field_headers(): @pytest.mark.asyncio async def test_list_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -564,7 +586,6 @@ async def test_list_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse() ) - await client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -578,13 +599,12 @@ async def test_list_documents_field_headers_async(): def test_list_documents_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_documents(parent="parent_value",) @@ -593,12 +613,11 @@ def test_list_documents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_documents_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -610,7 +629,7 @@ def test_list_documents_flattened_error(): @pytest.mark.asyncio async def test_list_documents_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -628,13 +647,12 @@ async def test_list_documents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_documents_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -645,7 +663,7 @@ async def test_list_documents_flattened_error_async(): def test_list_documents_pager(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -683,7 +701,7 @@ def test_list_documents_pager(): def test_list_documents_pages(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -713,7 +731,7 @@ def test_list_documents_pages(): @pytest.mark.asyncio async def test_list_documents_async_pager(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -750,7 +768,7 @@ async def test_list_documents_async_pager(): @pytest.mark.asyncio async def test_list_documents_async_pages(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -786,7 +804,7 @@ def test_get_document( transport: str = "grpc", request_type=document.GetDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -804,27 +822,19 @@ def test_get_document( enable_auto_reload=True, content_uri="content_uri_value", ) - response = client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -836,7 +846,7 @@ def test_get_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -844,7 +854,6 @@ def test_get_document_empty_call(): client.get_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() @@ -853,7 +862,7 @@ async def test_get_document_async( transport: str = "grpc_asyncio", request_type=document.GetDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -872,26 +881,19 @@ async def test_get_document_async( enable_auto_reload=True, ) ) - response = await client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -901,17 +903,17 @@ async def test_get_document_async_from_dict(): def test_get_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = document.Document() - client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -926,17 +928,17 @@ def test_get_document_field_headers(): @pytest.mark.asyncio async def test_get_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -950,13 +952,12 @@ async def test_get_document_field_headers_async(): def test_get_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_document(name="name_value",) @@ -965,12 +966,11 @@ def test_get_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -982,7 +982,7 @@ def test_get_document_flattened_error(): @pytest.mark.asyncio async def test_get_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: @@ -998,13 +998,12 @@ async def test_get_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1018,7 +1017,7 @@ def test_create_document( transport: str = "grpc", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1029,13 +1028,11 @@ def test_create_document( with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1050,7 +1047,7 @@ def test_create_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1055,6 @@ def test_create_document_empty_call(): client.create_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() @@ -1067,7 +1063,7 @@ async def test_create_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1080,13 +1076,11 @@ async def test_create_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1099,17 +1093,17 @@ async def test_create_document_async_from_dict(): def test_create_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1124,11 +1118,12 @@ def test_create_document_field_headers(): @pytest.mark.asyncio async def test_create_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1136,7 +1131,6 @@ async def test_create_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1150,13 +1144,12 @@ async def test_create_document_field_headers_async(): def test_create_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_document( @@ -1167,14 +1160,12 @@ def test_create_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") def test_create_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1188,7 +1179,7 @@ def test_create_document_flattened_error(): @pytest.mark.asyncio async def test_create_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: @@ -1208,15 +1199,13 @@ async def test_create_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") @pytest.mark.asyncio async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1232,7 +1221,7 @@ def test_import_documents( transport: str = "grpc", request_type=document.ImportDocumentsRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1243,13 +1232,11 @@ def test_import_documents( with mock.patch.object(type(client.transport.import_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() # Establish that the response is the type that we expect. @@ -1264,7 +1251,7 @@ def test_import_documents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1272,7 +1259,6 @@ def test_import_documents_empty_call(): client.import_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() @@ -1281,7 +1267,7 @@ async def test_import_documents_async( transport: str = "grpc_asyncio", request_type=document.ImportDocumentsRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1294,13 +1280,11 @@ async def test_import_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() # Establish that the response is the type that we expect. @@ -1313,17 +1297,17 @@ async def test_import_documents_async_from_dict(): def test_import_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ImportDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_documents), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_documents(request) # Establish that the underlying gRPC stub method was called. @@ -1338,11 +1322,12 @@ def test_import_documents_field_headers(): @pytest.mark.asyncio async def test_import_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ImportDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1350,7 +1335,6 @@ async def test_import_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_documents(request) # Establish that the underlying gRPC stub method was called. @@ -1367,7 +1351,7 @@ def test_delete_document( transport: str = "grpc", request_type=document.DeleteDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1378,13 +1362,11 @@ def test_delete_document( with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1399,7 +1381,7 @@ def test_delete_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1407,7 +1389,6 @@ def test_delete_document_empty_call(): client.delete_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() @@ -1416,7 +1397,7 @@ async def test_delete_document_async( transport: str = "grpc_asyncio", request_type=document.DeleteDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1429,13 +1410,11 @@ async def test_delete_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1448,17 +1427,17 @@ async def test_delete_document_async_from_dict(): def test_delete_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1473,11 +1452,12 @@ def test_delete_document_field_headers(): @pytest.mark.asyncio async def test_delete_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1485,7 +1465,6 @@ async def test_delete_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1499,13 +1478,12 @@ async def test_delete_document_field_headers_async(): def test_delete_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_document(name="name_value",) @@ -1514,12 +1492,11 @@ def test_delete_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1531,7 +1508,7 @@ def test_delete_document_flattened_error(): @pytest.mark.asyncio async def test_delete_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: @@ -1549,13 +1526,12 @@ async def test_delete_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1569,7 +1545,7 @@ def test_update_document( transport: str = "grpc", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1580,13 +1556,11 @@ def test_update_document( with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1601,7 +1575,7 @@ def test_update_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1609,7 +1583,6 @@ def test_update_document_empty_call(): client.update_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() @@ -1618,7 +1591,7 @@ async def test_update_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1631,13 +1604,11 @@ async def test_update_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1650,17 +1621,17 @@ async def test_update_document_async_from_dict(): def test_update_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1677,11 +1648,12 @@ def test_update_document_field_headers(): @pytest.mark.asyncio async def test_update_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1689,7 +1661,6 @@ async def test_update_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1705,32 +1676,29 @@ async def test_update_document_field_headers_async(): def test_update_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_document( document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == gcd_document.Document(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1738,13 +1706,13 @@ def test_update_document_flattened_error(): client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: @@ -1758,22 +1726,20 @@ async def test_update_document_flattened_async(): # using the keyword arguments to the method. response = await client.update_document( document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == gcd_document.Document(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1781,7 +1747,7 @@ async def test_update_document_flattened_error_async(): await client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1789,7 +1755,7 @@ def test_reload_document( transport: str = "grpc", request_type=document.ReloadDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1800,13 +1766,11 @@ def test_reload_document( with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1821,7 +1785,7 @@ def test_reload_document_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1829,7 +1793,6 @@ def test_reload_document_empty_call(): client.reload_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() @@ -1838,7 +1801,7 @@ async def test_reload_document_async( transport: str = "grpc_asyncio", request_type=document.ReloadDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1851,13 +1814,11 @@ async def test_reload_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1870,17 +1831,17 @@ async def test_reload_document_async_from_dict(): def test_reload_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1895,11 +1856,12 @@ def test_reload_document_field_headers(): @pytest.mark.asyncio async def test_reload_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1907,7 +1869,6 @@ async def test_reload_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1921,13 +1882,12 @@ async def test_reload_document_field_headers_async(): def test_reload_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.reload_document( @@ -1938,14 +1898,12 @@ def test_reload_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].gcs_source == gcs.GcsSource(uri="uri_value") def test_reload_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1959,7 +1917,7 @@ def test_reload_document_flattened_error(): @pytest.mark.asyncio async def test_reload_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: @@ -1979,15 +1937,13 @@ async def test_reload_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].gcs_source == gcs.GcsSource(uri="uri_value") @pytest.mark.asyncio async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2002,16 +1958,16 @@ async def test_reload_document_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -2021,7 +1977,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -2032,7 +1988,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DocumentsClient(transport=transport) assert client.transport is transport @@ -2041,13 +1997,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2059,23 +2015,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DocumentsGrpcTransport,) def test_documents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2087,7 +2043,7 @@ def test_documents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2111,15 +2067,40 @@ def test_documents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_documents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2135,19 +2116,36 @@ def test_documents_base_transport_with_credentials_file(): def test_documents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_documents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_documents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) DocumentsClient() adc.assert_called_once_with( scopes=( @@ -2158,14 +2156,38 @@ def test_documents_auth_adc(): ) -def test_documents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_documents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.DocumentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_documents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2175,12 +2197,123 @@ def test_documents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport], ) def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2222,7 +2355,7 @@ def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_documents_host_no_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2232,7 +2365,7 @@ def test_documents_host_no_port(): def test_documents_host_with_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2283,9 +2416,9 @@ def test_documents_transport_channel_mtls_with_client_cert_source(transport_clas mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2364,7 +2497,7 @@ def test_documents_transport_channel_mtls_with_adc(transport_class): def test_documents_grpc_lro_client(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2377,7 +2510,7 @@ def test_documents_grpc_lro_client(): def test_documents_grpc_lro_async_client(): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2392,7 +2525,6 @@ def test_document_path(): project = "squid" knowledge_base = "clam" document = "whelk" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2415,7 +2547,6 @@ def test_parse_document_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2436,7 +2567,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = DocumentsClient.common_folder_path(folder) assert expected == actual @@ -2455,7 +2585,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = DocumentsClient.common_organization_path(organization) assert expected == actual @@ -2474,7 +2603,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = DocumentsClient.common_project_path(project) assert expected == actual @@ -2494,7 +2622,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2521,7 +2648,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DocumentsTransport, "_prep_wrapped_messages" ) as prep: client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2530,6 +2657,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DocumentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py b/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py index 84f937bcb..93fdd6bbf 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,27 +23,57 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesAsyncClient from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesClient from google.cloud.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.services.entity_types import transports +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_entity_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -440,7 +469,7 @@ def test_list_entity_types( transport: str = "grpc", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -455,19 +484,15 @@ def test_list_entity_types( call.return_value = entity_type.ListEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -479,7 +504,7 @@ def test_list_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -489,7 +514,6 @@ def test_list_entity_types_empty_call(): client.list_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() @@ -498,7 +522,7 @@ async def test_list_entity_types_async( transport: str = "grpc_asyncio", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -515,18 +539,15 @@ async def test_list_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -536,11 +557,12 @@ async def test_list_entity_types_async_from_dict(): def test_list_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -548,7 +570,6 @@ def test_list_entity_types_field_headers(): type(client.transport.list_entity_types), "__call__" ) as call: call.return_value = entity_type.ListEntityTypesResponse() - client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -563,11 +584,12 @@ def test_list_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -577,7 +599,6 @@ async def test_list_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.ListEntityTypesResponse() ) - await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -591,7 +612,7 @@ async def test_list_entity_types_field_headers_async(): def test_list_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -599,7 +620,6 @@ def test_list_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_entity_types( @@ -610,14 +630,12 @@ def test_list_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" def test_list_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -631,7 +649,7 @@ def test_list_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -653,15 +671,13 @@ async def test_list_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -674,7 +690,7 @@ async def test_list_entity_types_flattened_error_async(): def test_list_entity_types_pager(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -716,7 +732,7 @@ def test_list_entity_types_pager(): def test_list_entity_types_pages(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -750,7 +766,7 @@ def test_list_entity_types_pages(): @pytest.mark.asyncio async def test_list_entity_types_async_pager(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -791,7 +807,7 @@ async def test_list_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_entity_types_async_pages(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -831,7 +847,7 @@ def test_get_entity_type( transport: str = "grpc", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -848,30 +864,22 @@ def test_get_entity_type( auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -883,7 +891,7 @@ def test_get_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -891,7 +899,6 @@ def test_get_entity_type_empty_call(): client.get_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() @@ -900,7 +907,7 @@ async def test_get_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -919,29 +926,22 @@ async def test_get_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -951,17 +951,17 @@ async def test_get_entity_type_async_from_dict(): def test_get_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: call.return_value = entity_type.EntityType() - client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -976,11 +976,12 @@ def test_get_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -988,7 +989,6 @@ async def test_get_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.EntityType() ) - await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1002,13 +1002,12 @@ async def test_get_entity_type_field_headers_async(): def test_get_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_entity_type( @@ -1019,14 +1018,12 @@ def test_get_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" def test_get_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1040,7 +1037,7 @@ def test_get_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: @@ -1060,15 +1057,13 @@ async def test_get_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1084,7 +1079,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcd_entity_type.CreateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1103,30 +1098,22 @@ def test_create_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1138,7 +1125,7 @@ def test_create_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1148,7 +1135,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() @@ -1158,7 +1144,7 @@ async def test_create_entity_type_async( request_type=gcd_entity_type.CreateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1179,29 +1165,22 @@ async def test_create_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1211,11 +1190,12 @@ async def test_create_entity_type_async_from_dict(): def test_create_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1223,7 +1203,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1238,11 +1217,12 @@ def test_create_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1252,7 +1232,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1266,7 +1245,7 @@ async def test_create_entity_type_field_headers_async(): def test_create_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1274,7 +1253,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_entity_type( @@ -1287,16 +1265,13 @@ def test_create_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" def test_create_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1311,7 +1286,7 @@ def test_create_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1335,17 +1310,14 @@ async def test_create_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1362,7 +1334,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcd_entity_type.UpdateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1381,30 +1353,22 @@ def test_update_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=True, ) - response = client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1416,7 +1380,7 @@ def test_update_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1426,7 +1390,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() @@ -1436,7 +1399,7 @@ async def test_update_entity_type_async( request_type=gcd_entity_type.UpdateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1457,29 +1420,22 @@ async def test_update_entity_type_async( enable_fuzzy_extraction=True, ) ) - response = await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1489,11 +1445,12 @@ async def test_update_entity_type_async_from_dict(): def test_update_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1501,7 +1458,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1518,11 +1474,12 @@ def test_update_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,7 +1489,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1548,7 +1504,7 @@ async def test_update_entity_type_field_headers_async(): def test_update_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1556,29 +1512,25 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_entity_type( entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1587,13 +1539,13 @@ def test_update_entity_type_flattened_error(): gcd_entity_type.UpdateEntityTypeRequest(), entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1610,24 +1562,21 @@ async def test_update_entity_type_flattened_async(): response = await client.update_entity_type( entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_value" - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1636,7 +1585,7 @@ async def test_update_entity_type_flattened_error_async(): gcd_entity_type.UpdateEntityTypeRequest(), entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1644,7 +1593,7 @@ def test_delete_entity_type( transport: str = "grpc", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1657,13 +1606,11 @@ def test_delete_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1678,7 +1625,7 @@ def test_delete_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1688,7 +1635,6 @@ def test_delete_entity_type_empty_call(): client.delete_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() @@ -1697,7 +1643,7 @@ async def test_delete_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1710,13 +1656,11 @@ async def test_delete_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1729,11 +1673,12 @@ async def test_delete_entity_type_async_from_dict(): def test_delete_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1741,7 +1686,6 @@ def test_delete_entity_type_field_headers(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = None - client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1756,11 +1700,12 @@ def test_delete_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1768,7 +1713,6 @@ async def test_delete_entity_type_field_headers_async(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1782,7 +1726,7 @@ async def test_delete_entity_type_field_headers_async(): def test_delete_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1790,7 +1734,6 @@ def test_delete_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_entity_type(name="name_value",) @@ -1799,12 +1742,11 @@ def test_delete_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1816,7 +1758,7 @@ def test_delete_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1834,13 +1776,12 @@ async def test_delete_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1854,7 +1795,7 @@ def test_batch_update_entity_types( transport: str = "grpc", request_type=entity_type.BatchUpdateEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1867,13 +1808,11 @@ def test_batch_update_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1888,7 +1827,7 @@ def test_batch_update_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1898,7 +1837,6 @@ def test_batch_update_entity_types_empty_call(): client.batch_update_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() @@ -1908,7 +1846,7 @@ async def test_batch_update_entity_types_async( request_type=entity_type.BatchUpdateEntityTypesRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1923,13 +1861,11 @@ async def test_batch_update_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1942,11 +1878,12 @@ async def test_batch_update_entity_types_async_from_dict(): def test_batch_update_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1954,7 +1891,6 @@ def test_batch_update_entity_types_field_headers(): type(client.transport.batch_update_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1969,11 +1905,12 @@ def test_batch_update_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_update_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1983,7 +1920,6 @@ async def test_batch_update_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2000,7 +1936,7 @@ def test_batch_delete_entity_types( transport: str = "grpc", request_type=entity_type.BatchDeleteEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,13 +1949,11 @@ def test_batch_delete_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2034,7 +1968,7 @@ def test_batch_delete_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1978,6 @@ def test_batch_delete_entity_types_empty_call(): client.batch_delete_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() @@ -2054,7 +1987,7 @@ async def test_batch_delete_entity_types_async( request_type=entity_type.BatchDeleteEntityTypesRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2069,13 +2002,11 @@ async def test_batch_delete_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2088,11 +2019,12 @@ async def test_batch_delete_entity_types_async_from_dict(): def test_batch_delete_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2100,7 +2032,6 @@ def test_batch_delete_entity_types_field_headers(): type(client.transport.batch_delete_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2115,11 +2046,12 @@ def test_batch_delete_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2129,7 +2061,6 @@ async def test_batch_delete_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2143,7 +2074,7 @@ async def test_batch_delete_entity_types_field_headers_async(): def test_batch_delete_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2151,7 +2082,6 @@ def test_batch_delete_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_entity_types( @@ -2162,14 +2092,12 @@ def test_batch_delete_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type_names == ["entity_type_names_value"] def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2183,7 +2111,7 @@ def test_batch_delete_entity_types_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2205,15 +2133,13 @@ async def test_batch_delete_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type_names == ["entity_type_names_value"] @pytest.mark.asyncio async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2229,7 +2155,7 @@ def test_batch_create_entities( transport: str = "grpc", request_type=entity_type.BatchCreateEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2242,13 +2168,11 @@ def test_batch_create_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2263,7 +2187,7 @@ def test_batch_create_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2273,7 +2197,6 @@ def test_batch_create_entities_empty_call(): client.batch_create_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() @@ -2282,7 +2205,7 @@ async def test_batch_create_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchCreateEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2297,13 +2220,11 @@ async def test_batch_create_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2316,11 +2237,12 @@ async def test_batch_create_entities_async_from_dict(): def test_batch_create_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2328,7 +2250,6 @@ def test_batch_create_entities_field_headers(): type(client.transport.batch_create_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2343,11 +2264,12 @@ def test_batch_create_entities_field_headers(): @pytest.mark.asyncio async def test_batch_create_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2357,7 +2279,6 @@ async def test_batch_create_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2371,7 +2292,7 @@ async def test_batch_create_entities_field_headers_async(): def test_batch_create_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2379,7 +2300,6 @@ def test_batch_create_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_create_entities( @@ -2392,16 +2312,13 @@ def test_batch_create_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_create_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2416,7 +2333,7 @@ def test_batch_create_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_create_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2440,17 +2357,14 @@ async def test_batch_create_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2467,7 +2381,7 @@ def test_batch_update_entities( transport: str = "grpc", request_type=entity_type.BatchUpdateEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2480,13 +2394,11 @@ def test_batch_update_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2501,7 +2413,7 @@ def test_batch_update_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2511,7 +2423,6 @@ def test_batch_update_entities_empty_call(): client.batch_update_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() @@ -2520,7 +2431,7 @@ async def test_batch_update_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchUpdateEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2535,13 +2446,11 @@ async def test_batch_update_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2554,11 +2463,12 @@ async def test_batch_update_entities_async_from_dict(): def test_batch_update_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2566,7 +2476,6 @@ def test_batch_update_entities_field_headers(): type(client.transport.batch_update_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2581,11 +2490,12 @@ def test_batch_update_entities_field_headers(): @pytest.mark.asyncio async def test_batch_update_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2595,7 +2505,6 @@ async def test_batch_update_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2609,7 +2518,7 @@ async def test_batch_update_entities_field_headers_async(): def test_batch_update_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2617,7 +2526,6 @@ def test_batch_update_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_update_entities( @@ -2630,16 +2538,13 @@ def test_batch_update_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_update_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2654,7 +2559,7 @@ def test_batch_update_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_update_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2678,17 +2583,14 @@ async def test_batch_update_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2705,7 +2607,7 @@ def test_batch_delete_entities( transport: str = "grpc", request_type=entity_type.BatchDeleteEntitiesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2718,13 +2620,11 @@ def test_batch_delete_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2739,7 +2639,7 @@ def test_batch_delete_entities_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2749,7 +2649,6 @@ def test_batch_delete_entities_empty_call(): client.batch_delete_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() @@ -2758,7 +2657,7 @@ async def test_batch_delete_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchDeleteEntitiesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2773,13 +2672,11 @@ async def test_batch_delete_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2792,11 +2689,12 @@ async def test_batch_delete_entities_async_from_dict(): def test_batch_delete_entities_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2804,7 +2702,6 @@ def test_batch_delete_entities_field_headers(): type(client.transport.batch_delete_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2819,11 +2716,12 @@ def test_batch_delete_entities_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entities_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = entity_type.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2833,7 +2731,6 @@ async def test_batch_delete_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2847,7 +2744,7 @@ async def test_batch_delete_entities_field_headers_async(): def test_batch_delete_entities_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2855,7 +2752,6 @@ def test_batch_delete_entities_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_entities( @@ -2868,16 +2764,13 @@ def test_batch_delete_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2892,7 +2785,7 @@ def test_batch_delete_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entities_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2916,17 +2809,14 @@ async def test_batch_delete_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2942,16 +2832,16 @@ async def test_batch_delete_entities_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -2961,7 +2851,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -2972,7 +2862,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EntityTypesClient(transport=transport) assert client.transport is transport @@ -2981,13 +2871,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2999,23 +2889,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EntityTypesGrpcTransport,) def test_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3027,7 +2917,7 @@ def test_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3054,15 +2944,40 @@ def test_entity_types_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3078,19 +2993,36 @@ def test_entity_types_base_transport_with_credentials_file(): def test_entity_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) EntityTypesClient() adc.assert_called_once_with( scopes=( @@ -3101,14 +3033,38 @@ def test_entity_types_auth_adc(): ) -def test_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -3118,12 +3074,127 @@ def test_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport], ) def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3165,7 +3236,7 @@ def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class def test_entity_types_host_no_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3175,7 +3246,7 @@ def test_entity_types_host_no_port(): def test_entity_types_host_with_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3226,9 +3297,9 @@ def test_entity_types_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3307,7 +3378,7 @@ def test_entity_types_transport_channel_mtls_with_adc(transport_class): def test_entity_types_grpc_lro_client(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3320,7 +3391,7 @@ def test_entity_types_grpc_lro_client(): def test_entity_types_grpc_lro_async_client(): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3334,7 +3405,6 @@ def test_entity_types_grpc_lro_async_client(): def test_entity_type_path(): project = "squid" entity_type = "clam" - expected = "projects/{project}/agent/entityTypes/{entity_type}".format( project=project, entity_type=entity_type, ) @@ -3356,7 +3426,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3377,7 +3446,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -3396,7 +3464,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -3415,7 +3482,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -3435,7 +3501,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3462,7 +3527,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3471,6 +3536,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_environments.py b/tests/unit/gapic/dialogflow_v2beta1/test_environments.py index 78bcf4104..3609394c2 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_environments.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_environments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.environments import ( EnvironmentsAsyncClient, @@ -38,8 +37,42 @@ from google.cloud.dialogflow_v2beta1.services.environments import EnvironmentsClient from google.cloud.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.services.environments import transports +from google.cloud.dialogflow_v2beta1.services.environments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.environments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +118,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +133,7 @@ def test_environments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -151,7 +184,7 @@ def test_environments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EnvironmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -435,7 +468,7 @@ def test_list_environments( transport: str = "grpc", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -450,19 +483,15 @@ def test_list_environments( call.return_value = environment.ListEnvironmentsResponse( next_page_token="next_page_token_value", ) - response = client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == "next_page_token_value" @@ -474,7 +503,7 @@ def test_list_environments_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -484,7 +513,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -493,7 +521,7 @@ async def test_list_environments_async( transport: str = "grpc_asyncio", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -510,18 +538,15 @@ async def test_list_environments_async( next_page_token="next_page_token_value", ) ) - response = await client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -531,11 +556,12 @@ async def test_list_environments_async_from_dict(): def test_list_environments_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +569,6 @@ def test_list_environments_field_headers(): type(client.transport.list_environments), "__call__" ) as call: call.return_value = environment.ListEnvironmentsResponse() - client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -558,11 +583,12 @@ def test_list_environments_field_headers(): @pytest.mark.asyncio async def test_list_environments_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -572,7 +598,6 @@ async def test_list_environments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.ListEnvironmentsResponse() ) - await client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -586,7 +611,7 @@ async def test_list_environments_field_headers_async(): def test_list_environments_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -594,7 +619,6 @@ def test_list_environments_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = environment.ListEnvironmentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_environments(parent="parent_value",) @@ -603,12 +627,11 @@ def test_list_environments_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_environments_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -620,7 +643,7 @@ def test_list_environments_flattened_error(): @pytest.mark.asyncio async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -640,13 +663,12 @@ async def test_list_environments_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_environments_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -657,7 +679,7 @@ async def test_list_environments_flattened_error_async(): def test_list_environments_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,7 +721,7 @@ def test_list_environments_pager(): def test_list_environments_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -733,7 +755,7 @@ def test_list_environments_pages(): @pytest.mark.asyncio async def test_list_environments_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -774,7 +796,7 @@ async def test_list_environments_async_pager(): @pytest.mark.asyncio async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -810,241 +832,1352 @@ async def test_list_environments_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), +def test_get_environment( + transport: str = "grpc", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, transport=transport, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + response = client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) +@pytest.mark.asyncio +async def test_get_environment_async( + transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) ) + response = await client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - ) + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("list_environments",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) -def test_environments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file" - ) as load_creds, mock.patch( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) +def test_get_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) -def test_environments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + request.name = "name/value" -def test_environments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id=None, - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + call.return_value = environment.Environment() + client.get_environment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_environments_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" - ) - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -@pytest.mark.parametrize( - "transport_class", - [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], -) -def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() +@pytest.mark.asyncio +async def test_get_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + request.name = "name/value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.get_environment(request) -def test_environments_host_no_port(): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="dialogflow.googleapis.com" - ), - ) - assert client.transport._host == "dialogflow.googleapis.com:443" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_environments_host_with_port(): + +def test_create_environment( + transport: str = "grpc", request_type=environment.CreateEnvironmentRequest +): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="dialogflow.googleapis.com:8000" - ), + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - assert client.transport._host == "dialogflow.googleapis.com:8000" - -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Check that channel is used if provided. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async( + transport: str = "grpc_asyncio", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_update_environment( + transport: str = "grpc", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async( + transport: str = "grpc_asyncio", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +def test_delete_environment( + transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async( + transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_environment_history( + transport: str = "grpc", request_type=environment.GetEnvironmentHistoryRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async( + transport: str = "grpc_asyncio", + request_type=environment.GetEnvironmentHistoryRequest, +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + ) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory() + ) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_get_environment_history_pager(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) for i in results) + + +def test_get_environment_history_pages(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, environment.EnvironmentHistory.Entry) for i in responses + ) + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) + + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_environments", + "get_environment", + "create_environment", + "update_environment", + "delete_environment", + "get_environment_history", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_environments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_environments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_environments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_environments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], +) +def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. transport = transports.EnvironmentsGrpcTransport( host="squid.clam.whelk", channel=channel, ) @@ -1084,9 +2217,9 @@ def test_environments_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1166,7 +2299,6 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environment_path(): project = "squid" environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format( project=project, environment=environment, ) @@ -1186,9 +2318,26 @@ def test_parse_environment_path(): assert expected == actual -def test_common_billing_account_path(): - billing_account = "oyster" +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1198,7 +2347,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -1208,8 +2357,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -1217,7 +2365,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = EnvironmentsClient.common_folder_path(**expected) @@ -1227,8 +2375,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -1236,7 +2383,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = EnvironmentsClient.common_organization_path(**expected) @@ -1246,8 +2393,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -1255,7 +2401,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = EnvironmentsClient.common_project_path(**expected) @@ -1265,9 +2411,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1277,8 +2422,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = EnvironmentsClient.common_location_path(**expected) @@ -1294,7 +2439,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EnvironmentsTransport, "_prep_wrapped_messages" ) as prep: client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1303,6 +2448,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EnvironmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py b/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py similarity index 70% rename from owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py rename to tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py index 974401ebc..899e4f128 100644 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py @@ -31,11 +31,17 @@ from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import ( + FulfillmentsAsyncClient, +) from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsClient from google.cloud.dialogflow_v2beta1.services.fulfillments import transports -from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import fulfillment from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment from google.oauth2 import service_account @@ -65,6 +71,7 @@ reason="This test requires google-api-core >= 1.26.0", ) + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -73,7 +80,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -84,36 +95,45 @@ def test__get_default_mtls_endpoint(): 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(api_endpoint) == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, - FulfillmentsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) def test_fulfillments_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, - FulfillmentsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) def test_fulfillments_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds @@ -123,7 +143,7 @@ def test_fulfillments_client_from_service_account_file(client_class): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_fulfillments_client_get_transport_class(): @@ -137,29 +157,42 @@ def test_fulfillments_client_get_transport_class(): assert transport == transports.FulfillmentsGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) -def test_fulfillments_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +def test_fulfillments_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch.object(FulfillmentsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + 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: + 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -175,7 +208,7 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -191,7 +224,7 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -211,13 +244,15 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans client = client_class() # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class() # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -230,24 +265,50 @@ def test_fulfillments_client_client_options(client_class, transport_class, trans client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +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: + 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) @@ -270,10 +331,18 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp # 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): + 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 @@ -294,9 +363,14 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -310,16 +384,23 @@ def test_fulfillments_client_mtls_env_auto(client_class, transport_class, transp ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_fulfillments_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -332,16 +413,24 @@ def test_fulfillments_client_client_options_scopes(client_class, transport_class client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -356,11 +445,11 @@ def test_fulfillments_client_client_options_credentials_file(client_class, trans def test_fulfillments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + 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'} - ) + client = FulfillmentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -372,10 +461,11 @@ def test_fulfillments_client_client_options_from_dict(): ) -def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): +def test_get_fulfillment( + transport: str = "grpc", request_type=fulfillment.GetFulfillmentRequest +): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -383,15 +473,15 @@ def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFu 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: + 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', + name="name_value", + display_name="display_name_value", enabled=True, - generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + generic_web_service=fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), ) response = client.get_fulfillment(request) @@ -402,8 +492,8 @@ def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFu # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -415,14 +505,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: client.get_fulfillment() call.assert_called() _, args, _ = call.mock_calls[0] @@ -430,10 +517,11 @@ def test_get_fulfillment_empty_call(): @pytest.mark.asyncio -async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): +async def test_get_fulfillment_async( + transport: str = "grpc_asyncio", request_type=fulfillment.GetFulfillmentRequest +): client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -441,15 +529,13 @@ async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_ty 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: + 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, - )) + 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. @@ -459,8 +545,8 @@ async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_ty # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -470,20 +556,16 @@ async def test_get_fulfillment_async_from_dict(): def test_get_fulfillment_field_headers(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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' + 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: + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: call.return_value = fulfillment.Fulfillment() client.get_fulfillment(request) @@ -494,29 +576,24 @@ def test_get_fulfillment_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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()) + 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. @@ -526,96 +603,78 @@ async def test_get_fulfillment_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_fulfillment_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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', - ) + client.get_fulfillment(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_get_fulfillment_flattened_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + fulfillment.GetFulfillmentRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_fulfillment_flattened_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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.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', - ) + response = await client.get_fulfillment(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_fulfillment_flattened_error_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + fulfillment.GetFulfillmentRequest(), name="name_value", ) -def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): +def test_update_fulfillment( + transport: str = "grpc", request_type=gcd_fulfillment.UpdateFulfillmentRequest +): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -624,14 +683,16 @@ def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillmen # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + 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', + name="name_value", + display_name="display_name_value", enabled=True, - generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), ) response = client.update_fulfillment(request) @@ -642,8 +703,8 @@ def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillmen # 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -655,14 +716,13 @@ 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', + 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: + type(client.transport.update_fulfillment), "__call__" + ) as call: client.update_fulfillment() call.assert_called() _, args, _ = call.mock_calls[0] @@ -670,10 +730,12 @@ def test_update_fulfillment_empty_call(): @pytest.mark.asyncio -async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): +async def test_update_fulfillment_async( + transport: str = "grpc_asyncio", + request_type=gcd_fulfillment.UpdateFulfillmentRequest, +): client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -682,14 +744,14 @@ async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + 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, - )) + 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. @@ -699,8 +761,8 @@ async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', 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.name == "name_value" + assert response.display_name == "display_name_value" assert response.enabled is True @@ -710,20 +772,18 @@ async def test_update_fulfillment_async_from_dict(): def test_update_fulfillment_field_headers(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_fulfillment.UpdateFulfillmentRequest() - request.fulfillment.name = 'fulfillment.name/value' + request.fulfillment.name = "fulfillment.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: + type(client.transport.update_fulfillment), "__call__" + ) as call: call.return_value = gcd_fulfillment.Fulfillment() client.update_fulfillment(request) @@ -734,29 +794,28 @@ def test_update_fulfillment_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'fulfillment.name=fulfillment.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] @pytest.mark.asyncio async def test_update_fulfillment_field_headers_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_fulfillment.UpdateFulfillmentRequest() - request.fulfillment.name = 'fulfillment.name/value' + request.fulfillment.name = "fulfillment.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_fulfillment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + 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. @@ -766,95 +825,88 @@ async def test_update_fulfillment_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'fulfillment.name=fulfillment.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] def test_update_fulfillment_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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: + 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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_fulfillment_flattened_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + 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(), - ) + 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: + 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.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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_fulfillment_flattened_error_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -865,8 +917,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -885,8 +936,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = FulfillmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client_options={"scopes": ["1", "2"]}, transport=transport, ) @@ -898,6 +948,7 @@ def test_transport_instance(): 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( @@ -912,39 +963,42 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FulfillmentsGrpcTransport, - ) + 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" + 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: + 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(), @@ -953,8 +1007,8 @@ def test_fulfillments_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_fulfillment', - 'update_fulfillment', + "get_fulfillment", + "update_fulfillment", ) for method in methods: with pytest.raises(NotImplementedError): @@ -964,19 +1018,23 @@ def test_fulfillments_base_transport(): @requires_google_auth_gte_1_25_0 def test_fulfillments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -984,16 +1042,21 @@ def test_fulfillments_base_transport_with_credentials_file(): @requires_google_auth_lt_1_25_0 def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), quota_project_id="octopus", ) @@ -1001,7 +1064,9 @@ def test_fulfillments_base_transport_with_credentials_file_old_google_auth(): 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: + 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() @@ -1011,15 +1076,15 @@ def test_fulfillments_base_transport_with_adc(): @requires_google_auth_gte_1_25_0 def test_fulfillments_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1027,11 +1092,14 @@ def test_fulfillments_auth_adc(): @requires_google_auth_lt_1_25_0 def test_fulfillments_auth_adc_old_google_auth(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) FulfillmentsClient() adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1047,12 +1115,15 @@ def test_fulfillments_auth_adc_old_google_auth(): 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: + 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',), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1071,10 +1142,11 @@ def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1083,22 +1155,21 @@ def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_gte_1_26_0 def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "dialogflow.googleapis.com:443", @@ -1106,9 +1177,9 @@ def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), scopes=["1", "2"], default_host="dialogflow.googleapis.com", ssl_credentials=None, @@ -1123,14 +1194,18 @@ def test_fulfillments_transport_create_channel(transport_class, grpc_helpers): "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 -def test_fulfillments_transport_create_channel_old_api_core(transport_class, grpc_helpers): +def test_fulfillments_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -1143,9 +1218,9 @@ def test_fulfillments_transport_create_channel_old_api_core(transport_class, grp credentials_file=None, quota_project_id="octopus", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), @@ -1158,14 +1233,18 @@ def test_fulfillments_transport_create_channel_old_api_core(transport_class, grp "transport_class,grpc_helpers", [ (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 -def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc_helpers): +def test_fulfillments_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -1187,10 +1266,11 @@ def test_fulfillments_transport_create_channel_user_scopes(transport_class, grpc ) -@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) -def test_fulfillments_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@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. @@ -1199,15 +1279,15 @@ def test_fulfillments_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, @@ -1223,37 +1303,40 @@ def test_fulfillments_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) def test_fulfillments_host_no_port(): client = FulfillmentsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_fulfillments_host_with_port(): client = FulfillmentsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' + assert client.transport._host == "dialogflow.googleapis.com:8000" + def test_fulfillments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1261,12 +1344,11 @@ def test_fulfillments_grpc_transport_channel(): def test_fulfillments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1275,12 +1357,17 @@ def test_fulfillments_grpc_asyncio_transport_channel(): # 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: +@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 @@ -1289,7 +1376,7 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1306,8 +1393,8 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -1322,17 +1409,20 @@ def test_fulfillments_transport_channel_mtls_with_client_cert_source( # 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 -): +@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: + 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() @@ -1350,8 +1440,8 @@ def test_fulfillments_transport_channel_mtls_with_adc( credentials=mock_cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -1365,7 +1455,7 @@ def test_fulfillments_transport_channel_mtls_with_adc( def test_fulfillment_path(): project = "squid" - expected = "projects/{project}/agent/fulfillment".format(project=project, ) + expected = "projects/{project}/agent/fulfillment".format(project=project,) actual = FulfillmentsClient.fulfillment_path(project) assert expected == actual @@ -1380,9 +1470,12 @@ def test_parse_fulfillment_path(): 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, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = FulfillmentsClient.common_billing_account_path(billing_account) assert expected == actual @@ -1397,9 +1490,10 @@ def test_parse_common_billing_account_path(): actual = FulfillmentsClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format(folder=folder,) actual = FulfillmentsClient.common_folder_path(folder) assert expected == actual @@ -1414,9 +1508,10 @@ def test_parse_common_folder_path(): actual = FulfillmentsClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format(organization=organization,) actual = FulfillmentsClient.common_organization_path(organization) assert expected == actual @@ -1431,9 +1526,10 @@ def test_parse_common_organization_path(): actual = FulfillmentsClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format(project=project,) actual = FulfillmentsClient.common_project_path(project) assert expected == actual @@ -1448,10 +1544,13 @@ def test_parse_common_project_path(): 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, ) + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) actual = FulfillmentsClient.common_location_path(project, location) assert expected == actual @@ -1471,17 +1570,19 @@ def test_parse_common_location_path(): def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + 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, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_intents.py b/tests/unit/gapic/dialogflow_v2beta1/test_intents.py index c922cc547..9e94c388e 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_intents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_intents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.intents import IntentsAsyncClient from google.cloud.dialogflow_v2beta1.services.intents import IntentsClient from google.cloud.dialogflow_v2beta1.services.intents import pagers from google.cloud.dialogflow_v2beta1.services.intents import transports +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_intents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_intents_client_get_transport_class(): def test_intents_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(IntentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_intents_client_client_options_from_dict(): def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -431,19 +460,15 @@ def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRe call.return_value = intent.ListIntentsResponse( next_page_token="next_page_token_value", ) - response = client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == "next_page_token_value" @@ -455,7 +480,7 @@ def test_list_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -463,7 +488,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -472,7 +496,7 @@ async def test_list_intents_async( transport: str = "grpc_asyncio", request_type=intent.ListIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,18 +509,15 @@ async def test_list_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListIntentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -506,17 +527,17 @@ async def test_list_intents_async_from_dict(): def test_list_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: call.return_value = intent.ListIntentsResponse() - client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -531,11 +552,12 @@ def test_list_intents_field_headers(): @pytest.mark.asyncio async def test_list_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ async def test_list_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse() ) - await client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -557,13 +578,12 @@ async def test_list_intents_field_headers_async(): def test_list_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_intents( @@ -574,14 +594,12 @@ def test_list_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" def test_list_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -595,7 +613,7 @@ def test_list_intents_flattened_error(): @pytest.mark.asyncio async def test_list_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -615,15 +633,13 @@ async def test_list_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -636,7 +652,7 @@ async def test_list_intents_flattened_error_async(): def test_list_intents_pager(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -668,7 +684,7 @@ def test_list_intents_pager(): def test_list_intents_pages(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -692,7 +708,7 @@ def test_list_intents_pages(): @pytest.mark.asyncio async def test_list_intents_async_pager(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -723,7 +739,7 @@ async def test_list_intents_async_pager(): @pytest.mark.asyncio async def test_list_intents_async_pages(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -751,7 +767,7 @@ async def test_list_intents_async_pages(): def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -779,51 +795,32 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -835,7 +832,7 @@ def test_get_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -843,7 +840,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -852,7 +848,7 @@ async def test_get_intent_async( transport: str = "grpc_asyncio", request_type=intent.GetIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -882,50 +878,32 @@ async def test_get_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -935,17 +913,17 @@ async def test_get_intent_async_from_dict(): def test_get_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = intent.Intent() - client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -960,17 +938,17 @@ def test_get_intent_field_headers(): @pytest.mark.asyncio async def test_get_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - await client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -984,13 +962,12 @@ async def test_get_intent_field_headers_async(): def test_get_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_intent( @@ -1001,14 +978,12 @@ def test_get_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" def test_get_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1022,7 +997,7 @@ def test_get_intent_flattened_error(): @pytest.mark.asyncio async def test_get_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: @@ -1040,15 +1015,13 @@ async def test_get_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1064,7 +1037,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcd_intent.CreateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1092,53 +1065,34 @@ def test_create_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1150,7 +1104,7 @@ def test_create_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1158,7 +1112,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() @@ -1167,7 +1120,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcd_intent.CreateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1199,52 +1152,34 @@ async def test_create_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1254,17 +1189,17 @@ async def test_create_intent_async_from_dict(): def test_create_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = gcd_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1279,17 +1214,17 @@ def test_create_intent_field_headers(): @pytest.mark.asyncio async def test_create_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1303,13 +1238,12 @@ async def test_create_intent_field_headers_async(): def test_create_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1322,16 +1256,13 @@ def test_create_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" def test_create_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1346,7 +1277,7 @@ def test_create_intent_flattened_error(): @pytest.mark.asyncio async def test_create_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: @@ -1366,17 +1297,14 @@ async def test_create_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1393,7 +1321,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcd_intent.UpdateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1421,53 +1349,34 @@ def test_update_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_value", ) - response = client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1479,7 +1388,7 @@ def test_update_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1487,7 +1396,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() @@ -1496,7 +1404,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcd_intent.UpdateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1528,52 +1436,34 @@ async def test_update_intent_async( parent_followup_intent_name="parent_followup_intent_name_value", ) ) - response = await client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1583,17 +1473,17 @@ async def test_update_intent_async_from_dict(): def test_update_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = gcd_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1608,17 +1498,17 @@ def test_update_intent_field_headers(): @pytest.mark.asyncio async def test_update_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1632,18 +1522,17 @@ async def test_update_intent_field_headers_async(): def test_update_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1651,16 +1540,13 @@ def test_update_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].language_code == "language_code_value" def test_update_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1668,14 +1554,14 @@ def test_update_intent_flattened_error(): client.update_intent( gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @pytest.mark.asyncio async def test_update_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: @@ -1687,7 +1573,7 @@ async def test_update_intent_flattened_async(): # using the keyword arguments to the method. response = await client.update_intent( intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1695,17 +1581,14 @@ async def test_update_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1713,7 +1596,7 @@ async def test_update_intent_flattened_error_async(): await client.update_intent( gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1722,7 +1605,7 @@ def test_delete_intent( transport: str = "grpc", request_type=intent.DeleteIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1733,13 +1616,11 @@ def test_delete_intent( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1754,7 +1635,7 @@ def test_delete_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1762,7 +1643,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1771,7 +1651,7 @@ async def test_delete_intent_async( transport: str = "grpc_asyncio", request_type=intent.DeleteIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1782,13 +1662,11 @@ async def test_delete_intent_async( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1801,17 +1679,17 @@ async def test_delete_intent_async_from_dict(): def test_delete_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = None - client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1826,17 +1704,17 @@ def test_delete_intent_field_headers(): @pytest.mark.asyncio async def test_delete_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1850,13 +1728,12 @@ async def test_delete_intent_field_headers_async(): def test_delete_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_intent(name="name_value",) @@ -1865,12 +1742,11 @@ def test_delete_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1882,7 +1758,7 @@ def test_delete_intent_flattened_error(): @pytest.mark.asyncio async def test_delete_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: @@ -1898,13 +1774,12 @@ async def test_delete_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1918,7 +1793,7 @@ def test_batch_update_intents( transport: str = "grpc", request_type=intent.BatchUpdateIntentsRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1931,13 +1806,11 @@ def test_batch_update_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1952,7 +1825,7 @@ def test_batch_update_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1962,7 +1835,6 @@ def test_batch_update_intents_empty_call(): client.batch_update_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() @@ -1971,7 +1843,7 @@ async def test_batch_update_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchUpdateIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1986,13 +1858,11 @@ async def test_batch_update_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -2005,11 +1875,12 @@ async def test_batch_update_intents_async_from_dict(): def test_batch_update_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2017,7 +1888,6 @@ def test_batch_update_intents_field_headers(): type(client.transport.batch_update_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2032,11 +1902,12 @@ def test_batch_update_intents_field_headers(): @pytest.mark.asyncio async def test_batch_update_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1917,6 @@ async def test_batch_update_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2060,7 +1930,7 @@ async def test_batch_update_intents_field_headers_async(): def test_batch_update_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2068,7 +1938,6 @@ def test_batch_update_intents_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_update_intents( @@ -2083,16 +1952,14 @@ def test_batch_update_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) def test_batch_update_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2109,7 +1976,7 @@ def test_batch_update_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_update_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2135,9 +2002,7 @@ async def test_batch_update_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) @@ -2145,7 +2010,7 @@ async def test_batch_update_intents_flattened_async(): @pytest.mark.asyncio async def test_batch_update_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2164,7 +2029,7 @@ def test_batch_delete_intents( transport: str = "grpc", request_type=intent.BatchDeleteIntentsRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2177,13 +2042,11 @@ def test_batch_delete_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2198,7 +2061,7 @@ def test_batch_delete_intents_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2208,7 +2071,6 @@ def test_batch_delete_intents_empty_call(): client.batch_delete_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() @@ -2217,7 +2079,7 @@ async def test_batch_delete_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchDeleteIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2232,13 +2094,11 @@ async def test_batch_delete_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2251,11 +2111,12 @@ async def test_batch_delete_intents_async_from_dict(): def test_batch_delete_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2263,7 +2124,6 @@ def test_batch_delete_intents_field_headers(): type(client.transport.batch_delete_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2278,11 +2138,12 @@ def test_batch_delete_intents_field_headers(): @pytest.mark.asyncio async def test_batch_delete_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = intent.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2292,7 +2153,6 @@ async def test_batch_delete_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2306,7 +2166,7 @@ async def test_batch_delete_intents_field_headers_async(): def test_batch_delete_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2314,7 +2174,6 @@ def test_batch_delete_intents_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_intents( @@ -2325,14 +2184,12 @@ def test_batch_delete_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] def test_batch_delete_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2346,7 +2203,7 @@ def test_batch_delete_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2368,15 +2225,13 @@ async def test_batch_delete_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] @pytest.mark.asyncio async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2391,16 +2246,16 @@ async def test_batch_delete_intents_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -2410,7 +2265,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -2421,7 +2276,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = IntentsClient(transport=transport) assert client.transport is transport @@ -2430,13 +2285,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.IntentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2448,23 +2303,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.IntentsGrpcTransport,) def test_intents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2476,7 +2331,7 @@ def test_intents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2500,15 +2355,40 @@ def test_intents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_intents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2524,19 +2404,36 @@ def test_intents_base_transport_with_credentials_file(): def test_intents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_intents_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) IntentsClient() adc.assert_called_once_with( scopes=( @@ -2547,14 +2444,38 @@ def test_intents_auth_adc(): ) -def test_intents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_intents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.IntentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_intents_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2564,12 +2485,123 @@ def test_intents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport], ) def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2611,7 +2643,7 @@ def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_intents_host_no_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2621,7 +2653,7 @@ def test_intents_host_no_port(): def test_intents_host_with_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2672,9 +2704,9 @@ def test_intents_transport_channel_mtls_with_client_cert_source(transport_class) mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2753,7 +2785,7 @@ def test_intents_transport_channel_mtls_with_adc(transport_class): def test_intents_grpc_lro_client(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2766,7 +2798,7 @@ def test_intents_grpc_lro_client(): def test_intents_grpc_lro_async_client(): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2781,7 +2813,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2805,7 +2836,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2827,7 +2857,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2848,7 +2877,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2867,7 +2895,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2886,7 +2913,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2906,7 +2932,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2933,7 +2958,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.IntentsTransport, "_prep_wrapped_messages" ) as prep: client = IntentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2942,6 +2967,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = IntentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py b/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py index 0e365bc42..91c74a0c1 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.knowledge_bases import ( KnowledgeBasesAsyncClient, @@ -40,10 +39,40 @@ ) from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.services.knowledge_bases import transports +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_knowledge_bases_client_from_service_account_info(client_class): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -164,7 +193,7 @@ def test_knowledge_bases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(KnowledgeBasesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -452,7 +481,7 @@ def test_list_knowledge_bases( transport: str = "grpc", request_type=knowledge_base.ListKnowledgeBasesRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -467,19 +496,15 @@ def test_list_knowledge_bases( call.return_value = knowledge_base.ListKnowledgeBasesResponse( next_page_token="next_page_token_value", ) - response = client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == "next_page_token_value" @@ -491,7 +516,7 @@ def test_list_knowledge_bases_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -501,7 +526,6 @@ def test_list_knowledge_bases_empty_call(): client.list_knowledge_bases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() @@ -511,7 +535,7 @@ async def test_list_knowledge_bases_async( request_type=knowledge_base.ListKnowledgeBasesRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -528,18 +552,15 @@ async def test_list_knowledge_bases_async( next_page_token="next_page_token_value", ) ) - response = await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -549,11 +570,12 @@ async def test_list_knowledge_bases_async_from_dict(): def test_list_knowledge_bases_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -561,7 +583,6 @@ def test_list_knowledge_bases_field_headers(): type(client.transport.list_knowledge_bases), "__call__" ) as call: call.return_value = knowledge_base.ListKnowledgeBasesResponse() - client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -576,11 +597,14 @@ def test_list_knowledge_bases_field_headers(): @pytest.mark.asyncio async def test_list_knowledge_bases_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ async def test_list_knowledge_bases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.ListKnowledgeBasesResponse() ) - await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -604,7 +627,7 @@ async def test_list_knowledge_bases_field_headers_async(): def test_list_knowledge_bases_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -612,7 +635,6 @@ def test_list_knowledge_bases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.ListKnowledgeBasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_knowledge_bases(parent="parent_value",) @@ -621,12 +643,11 @@ def test_list_knowledge_bases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -638,7 +659,9 @@ def test_list_knowledge_bases_flattened_error(): @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -658,13 +681,14 @@ async def test_list_knowledge_bases_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -675,7 +699,7 @@ async def test_list_knowledge_bases_flattened_error_async(): def test_list_knowledge_bases_pager(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -721,7 +745,7 @@ def test_list_knowledge_bases_pager(): def test_list_knowledge_bases_pages(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -759,7 +783,7 @@ def test_list_knowledge_bases_pages(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -804,7 +828,7 @@ async def test_list_knowledge_bases_async_pager(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -848,7 +872,7 @@ def test_get_knowledge_base( transport: str = "grpc", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -865,23 +889,17 @@ def test_get_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -893,7 +911,7 @@ def test_get_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -903,7 +921,6 @@ def test_get_knowledge_base_empty_call(): client.get_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() @@ -912,7 +929,7 @@ async def test_get_knowledge_base_async( transport: str = "grpc_asyncio", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -931,22 +948,17 @@ async def test_get_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -956,11 +968,12 @@ async def test_get_knowledge_base_async_from_dict(): def test_get_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -968,7 +981,6 @@ def test_get_knowledge_base_field_headers(): type(client.transport.get_knowledge_base), "__call__" ) as call: call.return_value = knowledge_base.KnowledgeBase() - client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -983,11 +995,14 @@ def test_get_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_get_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -997,7 +1012,6 @@ async def test_get_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.KnowledgeBase() ) - await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1011,7 +1025,7 @@ async def test_get_knowledge_base_field_headers_async(): def test_get_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1019,7 +1033,6 @@ def test_get_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_knowledge_base(name="name_value",) @@ -1028,12 +1041,11 @@ def test_get_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1045,7 +1057,9 @@ def test_get_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1065,13 +1079,14 @@ async def test_get_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1085,7 +1100,7 @@ def test_create_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1102,23 +1117,17 @@ def test_create_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1130,7 +1139,7 @@ def test_create_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1140,7 +1149,6 @@ def test_create_knowledge_base_empty_call(): client.create_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() @@ -1150,7 +1158,7 @@ async def test_create_knowledge_base_async( request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1169,22 +1177,17 @@ async def test_create_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1194,11 +1197,12 @@ async def test_create_knowledge_base_async_from_dict(): def test_create_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1206,7 +1210,6 @@ def test_create_knowledge_base_field_headers(): type(client.transport.create_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1221,11 +1224,14 @@ def test_create_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_create_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1235,7 +1241,6 @@ async def test_create_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1249,7 +1254,7 @@ async def test_create_knowledge_base_field_headers_async(): def test_create_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1257,7 +1262,6 @@ def test_create_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_knowledge_base( @@ -1269,16 +1273,14 @@ def test_create_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1292,7 +1294,9 @@ def test_create_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1315,9 +1319,7 @@ async def test_create_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) @@ -1325,7 +1327,9 @@ async def test_create_knowledge_base_flattened_async(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1341,7 +1345,7 @@ def test_delete_knowledge_base( transport: str = "grpc", request_type=knowledge_base.DeleteKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1354,13 +1358,11 @@ def test_delete_knowledge_base( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1375,7 +1377,7 @@ def test_delete_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1385,7 +1387,6 @@ def test_delete_knowledge_base_empty_call(): client.delete_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() @@ -1395,7 +1396,7 @@ async def test_delete_knowledge_base_async( request_type=knowledge_base.DeleteKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1408,13 +1409,11 @@ async def test_delete_knowledge_base_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1427,11 +1426,12 @@ async def test_delete_knowledge_base_async_from_dict(): def test_delete_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1439,7 +1439,6 @@ def test_delete_knowledge_base_field_headers(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = None - client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1454,11 +1453,14 @@ def test_delete_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_delete_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1466,7 +1468,6 @@ async def test_delete_knowledge_base_field_headers_async(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1480,7 +1481,7 @@ async def test_delete_knowledge_base_field_headers_async(): def test_delete_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1488,7 +1489,6 @@ def test_delete_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_knowledge_base(name="name_value",) @@ -1497,12 +1497,11 @@ def test_delete_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1514,7 +1513,9 @@ def test_delete_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1532,13 +1533,14 @@ async def test_delete_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1552,7 +1554,7 @@ def test_update_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1569,23 +1571,17 @@ def test_update_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1597,7 +1593,7 @@ def test_update_knowledge_base_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1607,7 +1603,6 @@ def test_update_knowledge_base_empty_call(): client.update_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() @@ -1617,7 +1612,7 @@ async def test_update_knowledge_base_async( request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1636,22 +1631,17 @@ async def test_update_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1661,11 +1651,12 @@ async def test_update_knowledge_base_async_from_dict(): def test_update_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1673,7 +1664,6 @@ def test_update_knowledge_base_field_headers(): type(client.transport.update_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1691,11 +1681,14 @@ def test_update_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_update_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1705,7 +1698,6 @@ async def test_update_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1722,7 +1714,7 @@ async def test_update_knowledge_base_field_headers_async(): def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1730,28 +1722,25 @@ def test_update_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1759,13 +1748,15 @@ def test_update_knowledge_base_flattened_error(): client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1781,24 +1772,24 @@ async def test_update_knowledge_base_flattened_async(): # using the keyword arguments to the method. response = await client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1806,23 +1797,23 @@ async def test_update_knowledge_base_flattened_error_async(): await client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1832,7 +1823,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1843,7 +1834,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = KnowledgeBasesClient(transport=transport) assert client.transport is transport @@ -1852,13 +1843,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1873,23 +1864,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.KnowledgeBasesGrpcTransport,) def test_knowledge_bases_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1901,7 +1892,7 @@ def test_knowledge_bases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1918,15 +1909,40 @@ def test_knowledge_bases_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1942,19 +1958,36 @@ def test_knowledge_bases_base_transport_with_credentials_file(): def test_knowledge_bases_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) KnowledgeBasesClient() adc.assert_called_once_with( scopes=( @@ -1965,14 +1998,44 @@ def test_knowledge_bases_auth_adc(): ) -def test_knowledge_bases_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.KnowledgeBasesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1982,6 +2045,121 @@ def test_knowledge_bases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1990,7 +2168,7 @@ def test_knowledge_bases_transport_auth_adc(): ], ) def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2032,7 +2210,7 @@ def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_cl def test_knowledge_bases_host_no_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2042,7 +2220,7 @@ def test_knowledge_bases_host_no_port(): def test_knowledge_bases_host_with_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2098,9 +2276,9 @@ def test_knowledge_bases_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2183,7 +2361,6 @@ def test_knowledge_bases_transport_channel_mtls_with_adc(transport_class): def test_knowledge_base_path(): project = "squid" knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2205,7 +2382,6 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2226,7 +2402,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = KnowledgeBasesClient.common_folder_path(folder) assert expected == actual @@ -2245,7 +2420,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = KnowledgeBasesClient.common_organization_path(organization) assert expected == actual @@ -2264,7 +2438,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = KnowledgeBasesClient.common_project_path(project) assert expected == actual @@ -2284,7 +2457,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2311,7 +2483,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.KnowledgeBasesTransport, "_prep_wrapped_messages" ) as prep: client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2320,6 +2492,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = KnowledgeBasesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_participants.py b/tests/unit/gapic/dialogflow_v2beta1/test_participants.py index 5e42b5752..121e37e78 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_participants.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.participants import ( ParticipantsAsyncClient, @@ -38,6 +37,12 @@ from google.cloud.dialogflow_v2beta1.services.participants import ParticipantsClient from google.cloud.dialogflow_v2beta1.services.participants import pagers from google.cloud.dialogflow_v2beta1.services.participants import transports +from google.cloud.dialogflow_v2beta1.services.participants.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.participants.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import context @@ -47,10 +52,34 @@ from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_participants_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -162,7 +191,7 @@ def test_participants_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ParticipantsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -446,7 +475,7 @@ def test_create_participant( transport: str = "grpc", request_type=gcd_participant.CreateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -463,23 +492,17 @@ def test_create_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -491,7 +514,7 @@ def test_create_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -501,7 +524,6 @@ def test_create_participant_empty_call(): client.create_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() @@ -511,7 +533,7 @@ async def test_create_participant_async( request_type=gcd_participant.CreateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -530,22 +552,17 @@ async def test_create_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -555,11 +572,12 @@ async def test_create_participant_async_from_dict(): def test_create_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -567,7 +585,6 @@ def test_create_participant_field_headers(): type(client.transport.create_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -582,11 +599,12 @@ def test_create_participant_field_headers(): @pytest.mark.asyncio async def test_create_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -596,7 +614,6 @@ async def test_create_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -610,7 +627,7 @@ async def test_create_participant_field_headers_async(): def test_create_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -618,7 +635,6 @@ def test_create_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_participant( @@ -630,14 +646,12 @@ def test_create_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") def test_create_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -651,7 +665,7 @@ def test_create_participant_flattened_error(): @pytest.mark.asyncio async def test_create_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -674,15 +688,13 @@ async def test_create_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") @pytest.mark.asyncio async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -698,7 +710,7 @@ def test_get_participant( transport: str = "grpc", request_type=participant.GetParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -713,23 +725,17 @@ def test_get_participant( role=participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -741,7 +747,7 @@ def test_get_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -749,7 +755,6 @@ def test_get_participant_empty_call(): client.get_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() @@ -758,7 +763,7 @@ async def test_get_participant_async( transport: str = "grpc_asyncio", request_type=participant.GetParticipantRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -775,22 +780,17 @@ async def test_get_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -800,17 +800,17 @@ async def test_get_participant_async_from_dict(): def test_get_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: call.return_value = participant.Participant() - client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -825,11 +825,12 @@ def test_get_participant_field_headers(): @pytest.mark.asyncio async def test_get_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -837,7 +838,6 @@ async def test_get_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.Participant() ) - await client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -851,13 +851,12 @@ async def test_get_participant_field_headers_async(): def test_get_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_participant(name="name_value",) @@ -866,12 +865,11 @@ def test_get_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -883,7 +881,7 @@ def test_get_participant_flattened_error(): @pytest.mark.asyncio async def test_get_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: @@ -901,13 +899,12 @@ async def test_get_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -921,7 +918,7 @@ def test_list_participants( transport: str = "grpc", request_type=participant.ListParticipantsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -936,19 +933,15 @@ def test_list_participants( call.return_value = participant.ListParticipantsResponse( next_page_token="next_page_token_value", ) - response = client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == "next_page_token_value" @@ -960,7 +953,7 @@ def test_list_participants_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -970,7 +963,6 @@ def test_list_participants_empty_call(): client.list_participants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() @@ -979,7 +971,7 @@ async def test_list_participants_async( transport: str = "grpc_asyncio", request_type=participant.ListParticipantsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -996,18 +988,15 @@ async def test_list_participants_async( next_page_token="next_page_token_value", ) ) - response = await client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListParticipantsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1017,11 +1006,12 @@ async def test_list_participants_async_from_dict(): def test_list_participants_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1029,7 +1019,6 @@ def test_list_participants_field_headers(): type(client.transport.list_participants), "__call__" ) as call: call.return_value = participant.ListParticipantsResponse() - client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1044,11 +1033,12 @@ def test_list_participants_field_headers(): @pytest.mark.asyncio async def test_list_participants_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1048,6 @@ async def test_list_participants_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListParticipantsResponse() ) - await client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1072,7 +1061,7 @@ async def test_list_participants_field_headers_async(): def test_list_participants_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1080,7 +1069,6 @@ def test_list_participants_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.ListParticipantsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_participants(parent="parent_value",) @@ -1089,12 +1077,11 @@ def test_list_participants_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_participants_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1106,7 +1093,7 @@ def test_list_participants_flattened_error(): @pytest.mark.asyncio async def test_list_participants_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1126,13 +1113,12 @@ async def test_list_participants_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_participants_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1143,7 +1129,7 @@ async def test_list_participants_flattened_error_async(): def test_list_participants_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1185,7 +1171,7 @@ def test_list_participants_pager(): def test_list_participants_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1219,7 +1205,7 @@ def test_list_participants_pages(): @pytest.mark.asyncio async def test_list_participants_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1260,7 +1246,7 @@ async def test_list_participants_async_pager(): @pytest.mark.asyncio async def test_list_participants_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1300,7 +1286,7 @@ def test_update_participant( transport: str = "grpc", request_type=gcd_participant.UpdateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1317,23 +1303,17 @@ def test_update_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -1345,7 +1325,7 @@ def test_update_participant_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1355,7 +1335,6 @@ def test_update_participant_empty_call(): client.update_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() @@ -1365,7 +1344,7 @@ async def test_update_participant_async( request_type=gcd_participant.UpdateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1384,22 +1363,17 @@ async def test_update_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -1409,11 +1383,12 @@ async def test_update_participant_async_from_dict(): def test_update_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1421,7 +1396,6 @@ def test_update_participant_field_headers(): type(client.transport.update_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1438,11 +1412,12 @@ def test_update_participant_field_headers(): @pytest.mark.asyncio async def test_update_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1452,7 +1427,6 @@ async def test_update_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1468,7 +1442,7 @@ async def test_update_participant_field_headers_async(): def test_update_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1476,26 +1450,23 @@ def test_update_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_participant( participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == gcd_participant.Participant(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1503,13 +1474,13 @@ def test_update_participant_flattened_error(): client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1525,22 +1496,20 @@ async def test_update_participant_flattened_async(): # using the keyword arguments to the method. response = await client.update_participant( participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == gcd_participant.Participant(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1548,7 +1517,7 @@ async def test_update_participant_flattened_error_async(): await client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1556,7 +1525,7 @@ def test_analyze_content( transport: str = "grpc", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1569,19 +1538,15 @@ def test_analyze_content( call.return_value = gcd_participant.AnalyzeContentResponse( reply_text="reply_text_value", ) - response = client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1593,7 +1558,7 @@ def test_analyze_content_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1601,7 +1566,6 @@ def test_analyze_content_empty_call(): client.analyze_content() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() @@ -1610,7 +1574,7 @@ async def test_analyze_content_async( transport: str = "grpc_asyncio", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1623,18 +1587,15 @@ async def test_analyze_content_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse(reply_text="reply_text_value",) ) - response = await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1644,17 +1605,17 @@ async def test_analyze_content_async_from_dict(): def test_analyze_content_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: call.return_value = gcd_participant.AnalyzeContentResponse() - client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1669,11 +1630,12 @@ def test_analyze_content_field_headers(): @pytest.mark.asyncio async def test_analyze_content_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1681,7 +1643,6 @@ async def test_analyze_content_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse() ) - await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1695,13 +1656,12 @@ async def test_analyze_content_field_headers_async(): def test_analyze_content_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.AnalyzeContentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_content( @@ -1714,14 +1674,12 @@ def test_analyze_content_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") def test_analyze_content_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1736,7 +1694,7 @@ def test_analyze_content_flattened_error(): @pytest.mark.asyncio async def test_analyze_content_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: @@ -1758,15 +1716,13 @@ async def test_analyze_content_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") @pytest.mark.asyncio async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1783,7 +1739,7 @@ def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1796,21 +1752,16 @@ def test_suggest_articles( call.return_value = participant.SuggestArticlesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1822,7 +1773,7 @@ def test_suggest_articles_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1830,7 +1781,6 @@ def test_suggest_articles_empty_call(): client.suggest_articles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() @@ -1839,7 +1789,7 @@ async def test_suggest_articles_async( transport: str = "grpc_asyncio", request_type=participant.SuggestArticlesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1854,20 +1804,16 @@ async def test_suggest_articles_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1877,17 +1823,17 @@ async def test_suggest_articles_async_from_dict(): def test_suggest_articles_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: call.return_value = participant.SuggestArticlesResponse() - client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1902,11 +1848,12 @@ def test_suggest_articles_field_headers(): @pytest.mark.asyncio async def test_suggest_articles_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1914,7 +1861,6 @@ async def test_suggest_articles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestArticlesResponse() ) - await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1928,13 +1874,12 @@ async def test_suggest_articles_field_headers_async(): def test_suggest_articles_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestArticlesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_articles(parent="parent_value",) @@ -1943,12 +1888,11 @@ def test_suggest_articles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_articles_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1960,7 +1904,7 @@ def test_suggest_articles_flattened_error(): @pytest.mark.asyncio async def test_suggest_articles_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: @@ -1978,13 +1922,12 @@ async def test_suggest_articles_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1998,7 +1941,7 @@ def test_suggest_faq_answers( transport: str = "grpc", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,21 +1956,16 @@ def test_suggest_faq_answers( call.return_value = participant.SuggestFaqAnswersResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2039,7 +1977,7 @@ def test_suggest_faq_answers_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2049,7 +1987,6 @@ def test_suggest_faq_answers_empty_call(): client.suggest_faq_answers() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() @@ -2058,7 +1995,7 @@ async def test_suggest_faq_answers_async( transport: str = "grpc_asyncio", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2075,20 +2012,16 @@ async def test_suggest_faq_answers_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2098,11 +2031,12 @@ async def test_suggest_faq_answers_async_from_dict(): def test_suggest_faq_answers_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2110,7 +2044,6 @@ def test_suggest_faq_answers_field_headers(): type(client.transport.suggest_faq_answers), "__call__" ) as call: call.return_value = participant.SuggestFaqAnswersResponse() - client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2125,11 +2058,12 @@ def test_suggest_faq_answers_field_headers(): @pytest.mark.asyncio async def test_suggest_faq_answers_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2139,7 +2073,6 @@ async def test_suggest_faq_answers_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestFaqAnswersResponse() ) - await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2153,7 +2086,7 @@ async def test_suggest_faq_answers_field_headers_async(): def test_suggest_faq_answers_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2161,7 +2094,6 @@ def test_suggest_faq_answers_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestFaqAnswersResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_faq_answers(parent="parent_value",) @@ -2170,12 +2102,11 @@ def test_suggest_faq_answers_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2187,7 +2118,7 @@ def test_suggest_faq_answers_flattened_error(): @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2207,13 +2138,12 @@ async def test_suggest_faq_answers_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2227,7 +2157,7 @@ def test_suggest_smart_replies( transport: str = "grpc", request_type=participant.SuggestSmartRepliesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2242,21 +2172,16 @@ def test_suggest_smart_replies( call.return_value = participant.SuggestSmartRepliesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestSmartRepliesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2268,7 +2193,7 @@ def test_suggest_smart_replies_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2278,7 +2203,6 @@ def test_suggest_smart_replies_empty_call(): client.suggest_smart_replies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() @@ -2287,7 +2211,7 @@ async def test_suggest_smart_replies_async( transport: str = "grpc_asyncio", request_type=participant.SuggestSmartRepliesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2304,20 +2228,16 @@ async def test_suggest_smart_replies_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestSmartRepliesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2327,11 +2247,12 @@ async def test_suggest_smart_replies_async_from_dict(): def test_suggest_smart_replies_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestSmartRepliesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2339,7 +2260,6 @@ def test_suggest_smart_replies_field_headers(): type(client.transport.suggest_smart_replies), "__call__" ) as call: call.return_value = participant.SuggestSmartRepliesResponse() - client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. @@ -2354,11 +2274,12 @@ def test_suggest_smart_replies_field_headers(): @pytest.mark.asyncio async def test_suggest_smart_replies_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestSmartRepliesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2368,7 +2289,6 @@ async def test_suggest_smart_replies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestSmartRepliesResponse() ) - await client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. @@ -2382,7 +2302,7 @@ async def test_suggest_smart_replies_field_headers_async(): def test_suggest_smart_replies_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2390,7 +2310,6 @@ def test_suggest_smart_replies_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestSmartRepliesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_smart_replies(parent="parent_value",) @@ -2399,12 +2318,11 @@ def test_suggest_smart_replies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_smart_replies_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2416,7 +2334,7 @@ def test_suggest_smart_replies_flattened_error(): @pytest.mark.asyncio async def test_suggest_smart_replies_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2436,13 +2354,12 @@ async def test_suggest_smart_replies_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_suggest_smart_replies_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2456,7 +2373,7 @@ def test_list_suggestions( transport: str = "grpc", request_type=participant.ListSuggestionsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2469,19 +2386,15 @@ def test_list_suggestions( call.return_value = participant.ListSuggestionsResponse( next_page_token="next_page_token_value", ) - response = client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSuggestionsPager) - assert response.next_page_token == "next_page_token_value" @@ -2493,7 +2406,7 @@ def test_list_suggestions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2501,7 +2414,6 @@ def test_list_suggestions_empty_call(): client.list_suggestions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() @@ -2510,7 +2422,7 @@ async def test_list_suggestions_async( transport: str = "grpc_asyncio", request_type=participant.ListSuggestionsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2525,18 +2437,15 @@ async def test_list_suggestions_async( next_page_token="next_page_token_value", ) ) - response = await client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSuggestionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2546,17 +2455,17 @@ async def test_list_suggestions_async_from_dict(): def test_list_suggestions_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListSuggestionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: call.return_value = participant.ListSuggestionsResponse() - client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. @@ -2571,11 +2480,12 @@ def test_list_suggestions_field_headers(): @pytest.mark.asyncio async def test_list_suggestions_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListSuggestionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2583,7 +2493,6 @@ async def test_list_suggestions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListSuggestionsResponse() ) - await client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. @@ -2597,7 +2506,7 @@ async def test_list_suggestions_field_headers_async(): def test_list_suggestions_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: @@ -2635,7 +2544,7 @@ def test_list_suggestions_pager(): def test_list_suggestions_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: @@ -2665,7 +2574,7 @@ def test_list_suggestions_pages(): @pytest.mark.asyncio async def test_list_suggestions_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2702,7 +2611,7 @@ async def test_list_suggestions_async_pager(): @pytest.mark.asyncio async def test_list_suggestions_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2738,7 +2647,7 @@ def test_compile_suggestion( transport: str = "grpc", request_type=participant.CompileSuggestionRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2753,21 +2662,16 @@ def test_compile_suggestion( call.return_value = participant.CompileSuggestionResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.CompileSuggestionResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2779,7 +2683,7 @@ def test_compile_suggestion_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2789,7 +2693,6 @@ def test_compile_suggestion_empty_call(): client.compile_suggestion() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() @@ -2798,7 +2701,7 @@ async def test_compile_suggestion_async( transport: str = "grpc_asyncio", request_type=participant.CompileSuggestionRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2815,20 +2718,16 @@ async def test_compile_suggestion_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.CompileSuggestionResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2838,11 +2737,12 @@ async def test_compile_suggestion_async_from_dict(): def test_compile_suggestion_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.CompileSuggestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2850,7 +2750,6 @@ def test_compile_suggestion_field_headers(): type(client.transport.compile_suggestion), "__call__" ) as call: call.return_value = participant.CompileSuggestionResponse() - client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. @@ -2865,11 +2764,12 @@ def test_compile_suggestion_field_headers(): @pytest.mark.asyncio async def test_compile_suggestion_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.CompileSuggestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2879,7 +2779,6 @@ async def test_compile_suggestion_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.CompileSuggestionResponse() ) - await client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. @@ -2895,16 +2794,16 @@ async def test_compile_suggestion_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2914,7 +2813,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2925,7 +2824,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ParticipantsClient(transport=transport) assert client.transport is transport @@ -2934,13 +2833,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2955,23 +2854,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ParticipantsGrpcTransport,) def test_participants_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2983,7 +2882,7 @@ def test_participants_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3005,15 +2904,40 @@ def test_participants_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_participants_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3029,19 +2953,36 @@ def test_participants_base_transport_with_credentials_file(): def test_participants_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_participants_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_participants_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ParticipantsClient() adc.assert_called_once_with( scopes=( @@ -3052,14 +2993,44 @@ def test_participants_auth_adc(): ) -def test_participants_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ParticipantsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -3069,12 +3040,127 @@ def test_participants_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport], ) def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3116,7 +3202,7 @@ def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class def test_participants_host_no_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3126,7 +3212,7 @@ def test_participants_host_no_port(): def test_participants_host_with_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3177,9 +3263,9 @@ def test_participants_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3260,7 +3346,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -3285,7 +3370,6 @@ def test_document_path(): project = "cuttlefish" knowledge_base = "mussel" document = "winkle" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -3309,7 +3393,6 @@ def test_parse_document_path(): def test_intent_path(): project = "squid" intent = "clam" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -3333,7 +3416,6 @@ def test_message_path(): project = "oyster" conversation = "nudibranch" message = "cuttlefish" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -3358,7 +3440,6 @@ def test_participant_path(): project = "scallop" conversation = "abalone" participant = "squid" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format( project=project, conversation=conversation, participant=participant, ) @@ -3383,7 +3464,6 @@ def test_session_entity_type_path(): project = "oyster" session = "nudibranch" entity_type = "cuttlefish" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -3406,7 +3486,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3427,7 +3506,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = ParticipantsClient.common_folder_path(folder) assert expected == actual @@ -3446,7 +3524,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = ParticipantsClient.common_organization_path(organization) assert expected == actual @@ -3465,7 +3542,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = ParticipantsClient.common_project_path(project) assert expected == actual @@ -3485,7 +3561,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3512,7 +3587,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ParticipantsTransport, "_prep_wrapped_messages" ) as prep: client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3521,6 +3596,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ParticipantsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py b/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py index 62894918b..d9c893fba 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers from google.cloud.dialogflow_v2beta1.services.session_entity_types import transports +from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import session_entity_type from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_session_entity_type, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_session_entity_types_client_from_service_account_info(client_class): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_session_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionEntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -467,7 +496,7 @@ def test_list_session_entity_types( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,19 +511,15 @@ def test_list_session_entity_types( call.return_value = session_entity_type.ListSessionEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -506,7 +531,7 @@ def test_list_session_entity_types_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -516,7 +541,6 @@ def test_list_session_entity_types_empty_call(): client.list_session_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() @@ -526,7 +550,7 @@ async def test_list_session_entity_types_async( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,18 +567,15 @@ async def test_list_session_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -564,11 +585,14 @@ async def test_list_session_entity_types_async_from_dict(): def test_list_session_entity_types_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -576,7 +600,6 @@ def test_list_session_entity_types_field_headers(): type(client.transport.list_session_entity_types), "__call__" ) as call: call.return_value = session_entity_type.ListSessionEntityTypesResponse() - client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -592,12 +615,13 @@ def test_list_session_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_session_entity_types_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -607,7 +631,6 @@ async def test_list_session_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.ListSessionEntityTypesResponse() ) - await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -621,7 +644,9 @@ async def test_list_session_entity_types_field_headers_async(): def test_list_session_entity_types_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -629,7 +654,6 @@ def test_list_session_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.ListSessionEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_session_entity_types(parent="parent_value",) @@ -638,12 +662,13 @@ def test_list_session_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +681,7 @@ def test_list_session_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_session_entity_types_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -677,14 +702,13 @@ async def test_list_session_entity_types_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_session_entity_types_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -696,7 +720,7 @@ async def test_list_session_entity_types_flattened_error_async(): def test_list_session_entity_types_pager(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +768,7 @@ def test_list_session_entity_types_pager(): def test_list_session_entity_types_pages(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -783,7 +807,7 @@ def test_list_session_entity_types_pages(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pager(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +856,7 @@ async def test_list_session_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pages(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -878,7 +902,7 @@ def test_get_session_entity_type( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -894,21 +918,16 @@ def test_get_session_entity_type( name="name_value", entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -923,7 +942,7 @@ def test_get_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -933,7 +952,6 @@ def test_get_session_entity_type_empty_call(): client.get_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() @@ -943,7 +961,7 @@ async def test_get_session_entity_type_async( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -961,20 +979,16 @@ async def test_get_session_entity_type_async( entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -987,11 +1001,14 @@ async def test_get_session_entity_type_async_from_dict(): def test_get_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -999,7 +1016,6 @@ def test_get_session_entity_type_field_headers(): type(client.transport.get_session_entity_type), "__call__" ) as call: call.return_value = session_entity_type.SessionEntityType() - client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1015,12 +1031,13 @@ def test_get_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1030,7 +1047,6 @@ async def test_get_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.SessionEntityType() ) - await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1044,7 +1060,9 @@ async def test_get_session_entity_type_field_headers_async(): def test_get_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1052,7 +1070,6 @@ def test_get_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_session_entity_type(name="name_value",) @@ -1061,12 +1078,13 @@ def test_get_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1079,7 +1097,7 @@ def test_get_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,14 +1118,13 @@ async def test_get_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1123,7 +1140,7 @@ def test_create_session_entity_type( request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1139,21 +1156,16 @@ def test_create_session_entity_type( name="name_value", entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1168,7 +1180,7 @@ def test_create_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1178,7 +1190,6 @@ def test_create_session_entity_type_empty_call(): client.create_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1206,20 +1217,16 @@ async def test_create_session_entity_type_async( entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1232,11 +1239,14 @@ async def test_create_session_entity_type_async_from_dict(): def test_create_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1244,7 +1254,6 @@ def test_create_session_entity_type_field_headers(): type(client.transport.create_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1260,12 +1269,13 @@ def test_create_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1275,7 +1285,6 @@ async def test_create_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1289,7 +1298,9 @@ async def test_create_session_entity_type_field_headers_async(): def test_create_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1297,7 +1308,6 @@ def test_create_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_session_entity_type( @@ -1311,16 +1321,16 @@ def test_create_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1347,7 @@ def test_create_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1363,9 +1373,7 @@ async def test_create_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) @@ -1374,7 +1382,7 @@ async def test_create_session_entity_type_flattened_async(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1394,7 +1402,7 @@ def test_update_session_entity_type( request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1410,21 +1418,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1439,7 +1442,7 @@ def test_update_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1449,7 +1452,6 @@ def test_update_session_entity_type_empty_call(): client.update_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1459,7 +1461,7 @@ async def test_update_session_entity_type_async( request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1477,20 +1479,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1503,11 +1501,14 @@ async def test_update_session_entity_type_async_from_dict(): def test_update_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1516,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1534,12 +1534,13 @@ def test_update_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1549,7 +1550,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1566,7 +1566,9 @@ async def test_update_session_entity_type_field_headers_async(): def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1574,30 +1576,29 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_session_entity_type( session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1607,14 +1608,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,25 +1634,23 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcd_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1662,7 +1661,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1671,7 +1670,7 @@ def test_delete_session_entity_type( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1684,13 +1683,11 @@ def test_delete_session_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1705,7 +1702,7 @@ def test_delete_session_entity_type_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1715,7 +1712,6 @@ def test_delete_session_entity_type_empty_call(): client.delete_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() @@ -1725,7 +1721,7 @@ async def test_delete_session_entity_type_async( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1738,13 +1734,11 @@ async def test_delete_session_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1757,11 +1751,14 @@ async def test_delete_session_entity_type_async_from_dict(): def test_delete_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1769,7 +1766,6 @@ def test_delete_session_entity_type_field_headers(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = None - client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1785,12 +1781,13 @@ def test_delete_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1798,7 +1795,6 @@ async def test_delete_session_entity_type_field_headers_async(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1812,7 +1808,9 @@ async def test_delete_session_entity_type_field_headers_async(): def test_delete_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1820,7 +1818,6 @@ def test_delete_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_session_entity_type(name="name_value",) @@ -1829,12 +1826,13 @@ def test_delete_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1847,7 +1845,7 @@ def test_delete_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1866,14 +1864,13 @@ async def test_delete_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1887,16 +1884,16 @@ async def test_delete_session_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1906,7 +1903,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1917,7 +1914,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionEntityTypesClient(transport=transport) assert client.transport is transport @@ -1926,13 +1923,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1947,23 +1944,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.SessionEntityTypesGrpcTransport,) def test_session_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1975,7 +1974,7 @@ def test_session_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1992,15 +1991,40 @@ def test_session_entity_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_session_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2016,19 +2040,36 @@ def test_session_entity_types_base_transport_with_credentials_file(): def test_session_entity_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_session_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SessionEntityTypesClient() adc.assert_called_once_with( scopes=( @@ -2039,14 +2080,44 @@ def test_session_entity_types_auth_adc(): ) -def test_session_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_session_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionEntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2056,6 +2127,121 @@ def test_session_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2066,7 +2252,7 @@ def test_session_entity_types_transport_auth_adc(): def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2108,7 +2294,7 @@ def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( def test_session_entity_types_host_no_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2118,7 +2304,7 @@ def test_session_entity_types_host_no_port(): def test_session_entity_types_host_with_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2174,9 +2360,9 @@ def test_session_entity_types_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2260,7 +2446,6 @@ def test_session_entity_type_path(): project = "squid" session = "clam" entity_type = "whelk" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2285,7 +2470,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2306,7 +2490,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2325,7 +2508,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2344,7 +2526,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2364,7 +2545,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2391,7 +2571,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionEntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2400,6 +2580,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionEntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py b/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py index 81d572606..371acd141 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,17 +23,23 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflow_v2beta1.services.sessions import SessionsAsyncClient from google.cloud.dialogflow_v2beta1.services.sessions import SessionsClient from google.cloud.dialogflow_v2beta1.services.sessions import transports +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import context @@ -43,10 +48,34 @@ from google.cloud.dialogflow_v2beta1.types import session as gcd_session from google.cloud.dialogflow_v2beta1.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_sessions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_sessions_client_get_transport_class(): def test_sessions_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -426,7 +455,7 @@ def test_detect_intent( transport: str = "grpc", request_type=gcd_session.DetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -439,21 +468,16 @@ def test_detect_intent( call.return_value = gcd_session.DetectIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -465,7 +489,7 @@ def test_detect_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -473,7 +497,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() @@ -482,7 +505,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=gcd_session.DetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,20 +520,16 @@ async def test_detect_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -520,17 +539,17 @@ async def test_detect_intent_async_from_dict(): def test_detect_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: call.return_value = gcd_session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -545,11 +564,12 @@ def test_detect_intent_field_headers(): @pytest.mark.asyncio async def test_detect_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -557,7 +577,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -571,13 +590,12 @@ async def test_detect_intent_field_headers_async(): def test_detect_intent_flattened(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_session.DetectIntentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_intent( @@ -593,9 +611,7 @@ def test_detect_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -604,7 +620,7 @@ def test_detect_intent_flattened(): def test_detect_intent_flattened_error(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -622,7 +638,7 @@ def test_detect_intent_flattened_error(): @pytest.mark.asyncio async def test_detect_intent_flattened_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: @@ -647,9 +663,7 @@ async def test_detect_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -659,7 +673,7 @@ async def test_detect_intent_flattened_async(): @pytest.mark.asyncio async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -679,13 +693,12 @@ def test_streaming_detect_intent( transport: str = "grpc", request_type=session.StreamingDetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -694,13 +707,11 @@ def test_streaming_detect_intent( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([session.StreamingDetectIntentResponse()]) - response = client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -717,13 +728,12 @@ async def test_streaming_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.StreamingDetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -735,13 +745,11 @@ async def test_streaming_detect_intent_async( call.return_value.read = mock.AsyncMock( side_effect=[session.StreamingDetectIntentResponse()] ) - response = await client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -757,16 +765,16 @@ async def test_streaming_detect_intent_async_from_dict(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -776,7 +784,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -787,7 +795,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionsClient(transport=transport) assert client.transport is transport @@ -796,13 +804,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -814,23 +822,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SessionsGrpcTransport,) def test_sessions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -842,7 +850,7 @@ def test_sessions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -856,15 +864,40 @@ def test_sessions_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_sessions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -880,19 +913,36 @@ def test_sessions_base_transport_with_credentials_file(): def test_sessions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_sessions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SessionsClient() adc.assert_called_once_with( scopes=( @@ -903,14 +953,38 @@ def test_sessions_auth_adc(): ) -def test_sessions_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_sessions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_sessions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -920,12 +994,123 @@ def test_sessions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport], ) def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -967,7 +1152,7 @@ def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_sessions_host_no_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -977,7 +1162,7 @@ def test_sessions_host_no_port(): def test_sessions_host_with_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1028,9 +1213,9 @@ def test_sessions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1111,7 +1296,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -1136,7 +1320,6 @@ def test_document_path(): project = "cuttlefish" knowledge_base = "mussel" document = "winkle" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -1160,7 +1343,6 @@ def test_parse_document_path(): def test_intent_path(): project = "squid" intent = "clam" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -1183,7 +1365,6 @@ def test_parse_intent_path(): def test_session_path(): project = "oyster" session = "nudibranch" - expected = "projects/{project}/agent/sessions/{session}".format( project=project, session=session, ) @@ -1207,7 +1388,6 @@ def test_session_entity_type_path(): project = "winkle" session = "nautilus" entity_type = "scallop" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -1230,7 +1410,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1251,7 +1430,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1270,7 +1448,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1289,7 +1466,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1309,7 +1485,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1336,7 +1511,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionsTransport, "_prep_wrapped_messages" ) as prep: client = SessionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1345,6 +1520,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py b/tests/unit/gapic/dialogflow_v2beta1/test_versions.py similarity index 67% rename from owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py rename to tests/unit/gapic/dialogflow_v2beta1/test_versions.py index e3fb07f88..d529189a9 100644 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_versions.py @@ -35,8 +35,12 @@ from google.cloud.dialogflow_v2beta1.services.versions import VersionsClient from google.cloud.dialogflow_v2beta1.services.versions import pagers from google.cloud.dialogflow_v2beta1.services.versions import transports -from google.cloud.dialogflow_v2beta1.services.versions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflow_v2beta1.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import version from google.cloud.dialogflow_v2beta1.types import version as gcd_version from google.oauth2 import service_account @@ -67,6 +71,7 @@ reason="This test requires google-api-core >= 1.26.0", ) + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -75,7 +80,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -87,35 +96,42 @@ def test__get_default_mtls_endpoint(): 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(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds @@ -125,7 +141,7 @@ def test_versions_client_from_service_account_file(client_class): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_versions_client_get_transport_class(): @@ -139,29 +155,36 @@ def test_versions_client_get_transport_class(): assert transport == transports.VersionsGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) def test_versions_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + 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: + 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -177,7 +200,7 @@ def test_versions_client_client_options(client_class, transport_class, transport # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -193,7 +216,7 @@ def test_versions_client_client_options(client_class, transport_class, transport # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -213,13 +236,15 @@ def test_versions_client_client_options(client_class, transport_class, transport client = client_class() # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class() # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -232,24 +257,50 @@ def test_versions_client_client_options(client_class, transport_class, transport client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +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: + 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) @@ -272,10 +323,18 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ # 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): + 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 @@ -296,9 +355,14 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class() patched.assert_called_once_with( @@ -312,16 +376,19 @@ def test_versions_client_mtls_env_auto(client_class, transport_class, transport_ ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -334,16 +401,20 @@ def test_versions_client_client_options_scopes(client_class, transport_class, tr client_info=transports.base.DEFAULT_CLIENT_INFO, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_credentials_file( + client_class, transport_class, transport_name +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( @@ -358,11 +429,11 @@ def test_versions_client_client_options_credentials_file(client_class, transport def test_versions_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + 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'} - ) + client = VersionsClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -374,10 +445,11 @@ def test_versions_client_client_options_from_dict(): ) -def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): +def test_list_versions( + transport: str = "grpc", request_type=version.ListVersionsRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -385,12 +457,10 @@ def test_list_versions(transport: str = 'grpc', request_type=version.ListVersion 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: + 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', + next_page_token="next_page_token_value", ) response = client.list_versions(request) @@ -401,7 +471,7 @@ def test_list_versions(transport: str = 'grpc', request_type=version.ListVersion # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_versions_from_dict(): @@ -412,14 +482,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: client.list_versions() call.assert_called() _, args, _ = call.mock_calls[0] @@ -427,10 +494,11 @@ def test_list_versions_empty_call(): @pytest.mark.asyncio -async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): +async def test_list_versions_async( + transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -438,13 +506,11 @@ async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type 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: + 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', - )) + 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. @@ -454,7 +520,7 @@ async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio @@ -463,20 +529,16 @@ async def test_list_versions_async_from_dict(): def test_list_versions_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.ListVersionsRequest() - request.parent = 'parent/value' + 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: + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: call.return_value = version.ListVersionsResponse() client.list_versions(request) @@ -487,29 +549,24 @@ def test_list_versions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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()) + 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. @@ -519,135 +576,97 @@ async def test_list_versions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_list_versions_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', - ) + client.list_versions(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' + assert args[0].parent == "parent_value" def test_list_versions_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.ListVersionsRequest(), parent="parent_value", ) @pytest.mark.asyncio async def test_list_versions_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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.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', - ) + response = await client.list_versions(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' + assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_versions_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.ListVersionsRequest(), parent="parent_value", ) def test_list_versions_pager(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_versions(request={}) @@ -655,146 +674,100 @@ def test_list_versions_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) + assert all(isinstance(i, version.Version) for i in results) + def test_list_versions_pages(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) pages = list(client.list_versions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + 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, - ) + 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: + 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', + 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', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) async_pager = await client.list_versions(request={},) - assert async_pager.next_page_token == 'abc' + assert async_pager.next_page_token == "abc" responses = [] async for response in async_pager: responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, version.Version) - for i in responses) + 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, - ) + 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: + 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', + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", ), + version.ListVersionsResponse(versions=[], next_page_token="def",), version.ListVersionsResponse( - versions=[], - next_page_token='def', + versions=[version.Version(),], next_page_token="ghi", ), version.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - version.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], + versions=[version.Version(), version.Version(),], ), RuntimeError, ) pages = [] async for page_ in (await client.list_versions(request={})).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + +def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,13 +775,11 @@ def test_get_version(transport: str = 'grpc', request_type=version.GetVersionReq 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=version.Version.VersionStatus.IN_PROGRESS, ) @@ -821,8 +792,8 @@ def test_get_version(transport: str = 'grpc', request_type=version.GetVersionReq # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == version.Version.VersionStatus.IN_PROGRESS @@ -835,14 +806,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.get_version), "__call__") as call: client.get_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -850,10 +818,11 @@ def test_get_version_empty_call(): @pytest.mark.asyncio -async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): +async def test_get_version_async( + transport: str = "grpc_asyncio", request_type=version.GetVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -861,16 +830,16 @@ async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=v 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: + 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, - )) + 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. @@ -880,8 +849,8 @@ async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=v # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == version.Version.VersionStatus.IN_PROGRESS @@ -892,20 +861,16 @@ async def test_get_version_async_from_dict(): def test_get_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.GetVersionRequest() - request.name = 'name/value' + 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: + with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = version.Version() client.get_version(request) @@ -916,28 +881,21 @@ def test_get_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -948,96 +906,76 @@ async def test_get_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: + 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', - ) + client.get_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_get_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.GetVersionRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_version_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: + 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', - ) + response = await client.get_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.GetVersionRequest(), name="name_value", ) -def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): +def test_create_version( + transport: str = "grpc", request_type=gcd_version.CreateVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1045,13 +983,11 @@ def test_create_version(transport: str = 'grpc', request_type=gcd_version.Create 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=gcd_version.Version.VersionStatus.IN_PROGRESS, ) @@ -1064,8 +1000,8 @@ def test_create_version(transport: str = 'grpc', request_type=gcd_version.Create # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1078,14 +1014,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.create_version), "__call__") as call: client.create_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1093,10 +1026,11 @@ def test_create_version_empty_call(): @pytest.mark.asyncio -async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): +async def test_create_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.CreateVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1104,16 +1038,16 @@ async def test_create_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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, - )) + 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. @@ -1123,8 +1057,8 @@ async def test_create_version_async(transport: str = 'grpc_asyncio', request_typ # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1135,20 +1069,16 @@ async def test_create_version_async_from_dict(): def test_create_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.CreateVersionRequest() - request.parent = 'parent/value' + 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: + with mock.patch.object(type(client.transport.create_version), "__call__") as call: call.return_value = gcd_version.Version() client.create_version(request) @@ -1159,28 +1089,21 @@ def test_create_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -1191,63 +1114,49 @@ async def test_create_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_create_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: + 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'), + parent="parent_value", version=gcd_version.Version(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") def test_create_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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'), + 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(), - ) + 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: + 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() @@ -1255,38 +1164,36 @@ async def test_create_version_flattened_async(): # 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'), + parent="parent_value", version=gcd_version.Version(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].version == gcd_version.Version(name='name_value') + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") @pytest.mark.asyncio async def test_create_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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'), + parent="parent_value", + version=gcd_version.Version(name="name_value"), ) -def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): +def test_update_version( + transport: str = "grpc", request_type=gcd_version.UpdateVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1294,13 +1201,11 @@ def test_update_version(transport: str = 'grpc', request_type=gcd_version.Update 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: + 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', + name="name_value", + description="description_value", version_number=1518, status=gcd_version.Version.VersionStatus.IN_PROGRESS, ) @@ -1313,8 +1218,8 @@ def test_update_version(transport: str = 'grpc', request_type=gcd_version.Update # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1327,14 +1232,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.update_version), "__call__") as call: client.update_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1342,10 +1244,11 @@ def test_update_version_empty_call(): @pytest.mark.asyncio -async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): +async def test_update_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.UpdateVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1353,16 +1256,16 @@ async def test_update_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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, - )) + 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. @@ -1372,8 +1275,8 @@ async def test_update_version_async(transport: str = 'grpc_asyncio', request_typ # 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.name == "name_value" + assert response.description == "description_value" assert response.version_number == 1518 assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS @@ -1384,20 +1287,16 @@ async def test_update_version_async_from_dict(): def test_update_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.UpdateVersionRequest() - request.version.name = 'version.name/value' + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + with mock.patch.object(type(client.transport.update_version), "__call__") as call: call.return_value = gcd_version.Version() client.update_version(request) @@ -1408,28 +1307,23 @@ def test_update_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'version.name=version.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] @pytest.mark.asyncio async def test_update_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_version.UpdateVersionRequest() - request.version.name = 'version.name/value' + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + 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) @@ -1440,63 +1334,52 @@ async def test_update_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'version.name=version.name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] def test_update_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: + 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].version == gcd_version.Version(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + 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(), - ) + 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: + 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() @@ -1504,38 +1387,37 @@ async def test_update_version_flattened_async(): # 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].version == gcd_version.Version(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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']), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): +def test_delete_version( + transport: str = "grpc", request_type=version.DeleteVersionRequest +): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1543,9 +1425,7 @@ def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVers 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: + 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) @@ -1567,14 +1447,11 @@ 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', + 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: + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: client.delete_version() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1582,10 +1459,11 @@ def test_delete_version_empty_call(): @pytest.mark.asyncio -async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): +async def test_delete_version_async( + transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest +): client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1593,9 +1471,7 @@ async def test_delete_version_async(transport: str = 'grpc_asyncio', request_typ 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: + 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) @@ -1615,20 +1491,16 @@ async def test_delete_version_async_from_dict(): def test_delete_version_field_headers(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = version.DeleteVersionRequest() - request.name = 'name/value' + 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: + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = None client.delete_version(request) @@ -1639,28 +1511,21 @@ def test_delete_version_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + 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(), - ) + 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' + 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: + 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) @@ -1671,89 +1536,68 @@ async def test_delete_version_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_delete_version_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: + 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', - ) + client.delete_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" def test_delete_version_flattened_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.DeleteVersionRequest(), name="name_value", ) @pytest.mark.asyncio async def test_delete_version_flattened_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: + 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', - ) + response = await client.delete_version(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' + assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_version_flattened_error_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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', + version.DeleteVersionRequest(), name="name_value", ) @@ -1764,8 +1608,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -1784,8 +1627,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = VersionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client_options={"scopes": ["1", "2"]}, transport=transport, ) @@ -1797,6 +1639,7 @@ def test_transport_instance(): 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( @@ -1811,39 +1654,39 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VersionsGrpcTransport, - ) + 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" + 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: + 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(), @@ -1852,11 +1695,11 @@ def test_versions_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_versions', - 'get_version', - 'create_version', - 'update_version', - 'delete_version', + "list_versions", + "get_version", + "create_version", + "update_version", + "delete_version", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1866,19 +1709,23 @@ def test_versions_base_transport(): @requires_google_auth_gte_1_25_0 def test_versions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1886,16 +1733,21 @@ def test_versions_base_transport_with_credentials_file(): @requires_google_auth_lt_1_25_0 def test_versions_base_transport_with_credentials_file_old_google_auth(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + 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", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), quota_project_id="octopus", ) @@ -1903,7 +1755,9 @@ def test_versions_base_transport_with_credentials_file_old_google_auth(): 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: + 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() @@ -1913,15 +1767,15 @@ def test_versions_base_transport_with_adc(): @requires_google_auth_gte_1_25_0 def test_versions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id=None, ) @@ -1929,42 +1783,42 @@ def test_versions_auth_adc(): @requires_google_auth_lt_1_25_0 def test_versions_auth_adc_old_google_auth(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) VersionsClient() adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + 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, - ], + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) @requires_google_auth_gte_1_25_0 def test_versions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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',), + 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) @requires_google_auth_lt_1_25_0 def test_versions_transport_auth_adc_old_google_auth(transport_class): @@ -1973,10 +1827,11 @@ def test_versions_transport_auth_adc_old_google_auth(transport_class): with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), quota_project_id="octopus", ) @@ -1985,22 +1840,21 @@ def test_versions_transport_auth_adc_old_google_auth(transport_class): "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_gte_1_26_0 def test_versions_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "dialogflow.googleapis.com:443", @@ -2008,9 +1862,9 @@ def test_versions_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), scopes=["1", "2"], default_host="dialogflow.googleapis.com", ssl_credentials=None, @@ -2025,14 +1879,16 @@ def test_versions_transport_create_channel(transport_class, grpc_helpers): "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 def test_versions_transport_create_channel_old_api_core(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -2045,9 +1901,9 @@ def test_versions_transport_create_channel_old_api_core(transport_class, grpc_he credentials_file=None, quota_project_id="octopus", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), @@ -2060,14 +1916,16 @@ def test_versions_transport_create_channel_old_api_core(transport_class, grpc_he "transport_class,grpc_helpers", [ (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), ], ) @requires_api_core_lt_1_26_0 def test_versions_transport_create_channel_user_scopes(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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() @@ -2089,10 +1947,11 @@ def test_versions_transport_create_channel_user_scopes(transport_class, grpc_hel ) -@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) -def test_versions_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@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. @@ -2101,15 +1960,15 @@ def test_versions_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, @@ -2125,37 +1984,40 @@ def test_versions_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) def test_versions_host_no_port(): client = VersionsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:443' + assert client.transport._host == "dialogflow.googleapis.com:443" def test_versions_host_with_port(): client = VersionsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), ) - assert client.transport._host == 'dialogflow.googleapis.com:8000' + assert client.transport._host == "dialogflow.googleapis.com:8000" + def test_versions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2163,12 +2025,11 @@ def test_versions_grpc_transport_channel(): def test_versions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + 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, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2177,12 +2038,17 @@ def test_versions_grpc_asyncio_transport_channel(): # 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: +@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 @@ -2191,7 +2057,7 @@ def test_versions_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2208,8 +2074,8 @@ def test_versions_transport_channel_mtls_with_client_cert_source( credentials=cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -2224,17 +2090,20 @@ def test_versions_transport_channel_mtls_with_client_cert_source( # 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 -): +@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: + 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() @@ -2252,8 +2121,8 @@ def test_versions_transport_channel_mtls_with_adc( credentials=mock_cred, credentials_file=None, scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", ), ssl_credentials=mock_ssl_cred, quota_project_id=None, @@ -2268,7 +2137,9 @@ def test_versions_transport_channel_mtls_with_adc( def test_version_path(): project = "squid" version = "clam" - expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + expected = "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) actual = VersionsClient.version_path(project, version) assert expected == actual @@ -2284,9 +2155,12 @@ def test_parse_version_path(): 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, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = VersionsClient.common_billing_account_path(billing_account) assert expected == actual @@ -2301,9 +2175,10 @@ def test_parse_common_billing_account_path(): actual = VersionsClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format(folder=folder,) actual = VersionsClient.common_folder_path(folder) assert expected == actual @@ -2318,9 +2193,10 @@ def test_parse_common_folder_path(): actual = VersionsClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format(organization=organization,) actual = VersionsClient.common_organization_path(organization) assert expected == actual @@ -2335,9 +2211,10 @@ def test_parse_common_organization_path(): actual = VersionsClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format(project=project,) actual = VersionsClient.common_project_path(project) assert expected == actual @@ -2352,10 +2229,13 @@ def test_parse_common_project_path(): 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, ) + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) actual = VersionsClient.common_location_path(project, location) assert expected == actual @@ -2375,17 +2255,19 @@ def test_parse_common_location_path(): def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + 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, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)